Bourne Shell Programming Topics Covered

Size: px
Start display at page:

Download "Bourne Shell Programming Topics Covered"

Transcription

1 Bourne Shell Programming Topics Covered Shell variables Using Quotes Arithmetic On Shell Passing Arguments Testing conditions Branching if-else, if-elif, case Looping while, for, until break and continue Using options using getopts Reading Data Environment and subshells Parameter substitution Using set I/O redirection Shell archives The eval, trap, wait commands 1

2 Part 1 Some Regular Expression Characters. (dot) any character ^ - beginning of line $ - end of line * - zero or more occurences of previous regular expression [chars] any character in the set of chars [^chars] any character not in chars. \{min,max\} at least min occurences and at most max occurences of the previous regular expression. 2

3 Shell Scripts Bourne Shell/Korn Shell Invoking a shell script $shell_script_file or $sh -options shell_script_file the script file must have execute-permission. Shell Variables mydir=/usr/jsmith/bin count= #assign a null value to the variable echo $mydir #display the contents of mvdir x=* echo $x #substitutes the names of the files in the directory #name of a command, options and arguments can be stored inside variables command=ls option=-l filename=namesfile $command $option $filename #shell performs the variable substitution before it # executes the command. 3 2

4 Quotes The Single Quote The white-space characters enclosed between the single quotes are preserved by the shell. The special characters are ignored. Example: filename=/usr/jsmith/bin/prog1 echo $filename echo $filename echo <> ; () {} ` & The Double Quote The special characters, $, back quotes (`) and back slashes (\) are not ignored. Example; x=* echo $x #filenames are substituted echo $x #$x is displayed echo $x # * is displayed, variable substitution is done inside the double quotes, no file name substitution is done and * is passed to the shell. 4

5 Quotes The Back Quote purpose is to tell the shell to execute the enclosed command and to insert the standard output from the command at that point on the command line. Example: echo The date and time is: `date` echo There are `who wc -l` users logged on filelist=`ls` echo $filelist (#what is the output) mail `sort -u names` < memo #-u option removes the duplicate # entries from the file The Back Slash Is same as putting single quotes around a single character. Quotes the single character that immediately follows it. X=* echo \$x # $x is displayed Is interpreted inside the double quotes. Use backslash inside the double quotes to remove the meaning of characters that otherwise would be interpreted. Examples: echo \$x #$x is displayed echo The value of x is \ $x\ #The value of x is 5 is displayed 5

6 Arithmetic On Shell A variable is just considered a string of characters. Example: x=1 x=$x+1 echo $x #will display 1+1 A unix program expr evaluates an expression given to it on the command line. Each operator and operand given to expr must be a separate argument. The operators, +, -, *, /, % are recognized. Example: i=1 i=`expr $i + 1` Evaluates only integer arithmetic expressions. awk may be used for floating point calculations. expr 10 * 2 # what is the problem with this? 6

7 Passing Arguments $#: Number of arguments passed to the program from the command line. $* : references all the arguments Example: %cat showargs echo $# arguments passed. echo they are :$*: %showargs a b c d 1 #output - %showargs a b c d 1 #output - % showargs `cat names` #output - % showargs x* #output - %cat lookup grep $1 phonebook lookup Mary Jones What is the result? 7

8 Positional Parameters Positional parameters set shell script arguments. e.g. $my_script a b xy positional parameters have the values $0 -- my_script $1 -- a $2 -- b $3 -- xy $ $* - references all the variables passed as arguments 8

9 The shift command shift left-shifts the positional parameters. If more than 9 arguments are supplied, arguments 10 and up cannot be referenced. use shift to access these arguments. shift assigns value in $2 into $1, $3 into $2 etc. The number of arguments ($#) gets decremented by one on each shift. %cat testshift echo $# $* shift echo $# $* shift echo $# $* % cat testshift What is the output? 9

10 Testing Conditions if statement: allows to test a condition and branch on the exit status of the condition tested. An exit status of 0 indicates the program executed successfully. An exit status of non-zero indicates a failure. $?: contains the exit status of the last command executed. Operators for integer comparisons eq (equal), -ge (greater than or equal), -gt (greater than), le (less than or equal), -lt (less than) and ne (not equal) Operators for string comparisons =,!=, -n (string is not null) and z (string is null) File operators -d file file is a directory -f file file is an ordinary file -r file file is readable by the process -s file is of non-zero length 10

11 Testing Conditions Examples user=$1 who grep ^$user > /dev/null - the exit status of the last command in the pipe line is returned. 11

12 The test command The test command is used to test one or more conditions in an if statement. y=abc test "$y" = ABC echo $? # displays 0 x= test -n x echo $? #displays 1 test -z x echo $? x=abc #checks if x is not null #checks if string is null [ "$x" = ABC ] #[] same as using test [! "$x" = ABC ] x=5 # -a for logical and -o for logical or [ "$x" -ge 0 -a "$x" -lt 10 ] [ -f $file1 -a -r $file1 ] 12

13 Branching %cat isuseron #checks if a user is logged on User=$1 if who grep $user #what is the problem with matching a username in the output of who? then echo $user is logged on fi ======================================== if [ $# -ne 1 ] #checking for the correct number of arguments then echo Incorrect number of args exit 1 #terminates the program with the exit status fi if [ $NAME = John Doe -a $BAL -gt 5000] then echo ok else echo not ok 13

14 Using case case: allows a comparison of a single character against other values and execute a command if a match is found. %cat ctype x=a case "$x #The value in x is compared with each of the cases #until a match is found. When a match is found, the #commands up to the double colons are executed. in [0-9] ) echo digit;; [A-Z] ) echo uppercase;; [a-z ) echo lowercase;; * ) echo special character;; esac Exercise: Can you rewrite the script passing the value to be tested as an argument? 14

15 The && and constructs command1 && command2 if the exit status of command 1 is 0 then command 2 is executed. Example EDITOR=[ -z "$EDITOR" ] && EDITOR=/bin/ed echo "$EDITOR" command1 command2 If the exit status of command 1 is not zero, then command 2 is executed. Example: grep $name phonebook echo Couldn t find name 15

16 Debugging with a -x option Trace the execution of any program by typing in sh -x followed by the name of the program and its arguments. Starts up a new shell to execute the program with the debug option. Commands are printed at the terminal as they are executed preceded by a + sign. sh -x ctype A + [ 1 -eq 1 ] + x=a + + echo A + wc -c num=2 + [ 2 -ne 1 ] + echo Enter a single character Enter a single character + exit 1

17 Looping The for loop is executed for as many words as are included after in for var in listofwords do commands done for i in do done echo $i for file in * #substitutes all the files in the do done processcmd $file # directory

18 The for loop for var #uses all the arguments given to the program on the command line do done command command for file in $* do done # Replaces $1, $2 as $1, $2 etc x=`wc -l $file` echo There are `echo $x cut -f1 -d ` lines in $file for file in $@ #Replaces $1, $2 as $1, $2 etc. Should be included in double quotes do done echo $file 18

19 Looping while command do done command1 command2 command1 and 2 are executed until command returns a nonzero exit status # Print command line arguments while [ $# -ne 0 ] do done echo $1 shift until command do done command1 command2 command1 and command2 are executed as long as command returns a non-zero exit status. until who grep ^$user do done sleep 60

20 Break and continue break: to break out of a loop. break n: to break out of n inner most loops for file do #variable error can be set to a value count=1 while [ $count -le 5 ] do #process file if [ -n $error ] #contains a value then break 2 fi count=`expr $count + 1` done done continue: the remaining commands in the loop are skipped. for file do if [! -f $file ] then fi done cat $file echo $file not found continue

21 The getopts command The built-in command, getopts processes the command line arguments. Format: getopts options variable Used in designing programs which take options. Example: isloggedon mary isloggedon -m mary isloggedon -m -t 120 mary isloggedon -t 120 -m mary The getopts command is designed to be executed inside a loop. 11

22 An example using getopts #wait until a specified user logs on -- version with options mailopt=false interval=60 #process command options using getopts while getopts mt: option do case "$option" in m) mailopt=true;; t) interval=$optarg;; \?) echo "Usage : mailto [-m] [-t n] user" exit 1;; esac done

23 An example using getopts (cont) #Make sure a user name is specified if [ "$OPTIND" -gt "$#" ] then echo "Missing user name" exit 2 fi #get the user name into $1 shiftcount=`expr $OPTIND - 1` shift $shiftcount #Check for user logging on # If the user is logged on, send mail (a reminder) if the mail option # is true. user=$1

24 Reading Data read variables shell reads a line from stdin and assigns the first word to the first variable, second word to the second variable etc.if there are more words than variables, the excess words are assigned to the last variable. Can redirect the input from a file. Examples: read x y #reads the input from the stdin read x y < names # reads the first line in names file and assigns the first word into x and the rest into y Example: while read val1 val2 do total=`expr $val1 + $val2` echo $total done 24

25 Copying a file using mycopy #check if two arguments are supplied. if not exit with an error message and usage fromfile="$1" tofile="$2" #check if the destination is a directory if [ -d "$tofile" ] then #extract the file name from the source file name and #concatenate it to the destination directory tofile=$tofile/`basename $fromfile` fi #check if a file with the destination file name exists if [ -f "$tofile" ] then echo "The file $tofile already exists. Do you want to overwrite it?" read $answer if [ "$answer"!= "yes" ] then exit 0 fi cp $fromfile $tofile 25 fi

26 $cat shelltest x=200 echo $x $shelltest x=100 SubShells #output is 200. The program shelltest executed in a # subshell. echo $x #output is 100 A subshell runs in its own environment with its own local variables. A subshell has no knowledge of the local variables in the parent shell, therefore cannot change the value of a variable in the parent shell. The command export is used to make the variables in a shell known to all subshells executed from that point. 26

27 $cat one echo x = $x y = $y $ one #x = y = are displayed since x and y have null values $ x=100 $ y=200 $ export y $ one #y=200 is displayed Once a variable is exported, it remains exported to all the subshells that are subsequently executed. Exported variables and their values are copied into a subshell s environment, where they may be accessed. Any changes made to them have no effect on the variables in the parent shell. A variable can be exported before or after it is assigned a value. 27

28 Subshells $cat one echo "x = $x" echo "y = $y" $cat two x=1 y=2 z=3 export z three $cat three echo "x = $x" echo "y = $y" echo "z = $z" $one $y=100 $export y $one $two $three #What is the output #What is the output # output # x = # y = #what is the output? # z = 3 why? #output # x = # y = 100 # z = Why? 28

29 Some Environment Variables PS1- stores the command prompt PS2 stores the secondary command prompt HOME Stores the home directory PATH contains a list of directories which the shell searches whenever you type in the name of the program to be executed. The PATH specifies the directories to be searched for programs to be executed and not for any other types of files. $ echo $PATH displays output which may look like this /bin:/usr/bin:: CDPATH 29

30 The set command Is used to set various shell options. Is used to reassign the positional parameters. Set with no arguments will give a list of all the variables that exist in your environment. HOME, PATH, SHELL are some of the variables that are displayed. Set can be used to reassign the positional parameters can be used to parse the data from a file or the terminal. Example: $cat testset set x y z echo $1: $2: $3 echo $# echo $* $testset x: y: z 3 x y z 30

31 Examples: $cat countwords read line set $line echo $# #reads a line of input from the terminal #each word in the input line is assigned # to a positional parameter #No. of words in the input line #A modified version of countwords read line set --$line #reads a line of input from the terminal #each word in the input line is assigned # to a positional parameter. With the option, an input line like = will not cause problems. echo $# 31

32 The eval command eval command-line shell scans the command line twice. Examples: $pipe= $ls $pipe wc l #will generate the errors - not found wc not found l not found The reason: Pipes and IO redirection is done before variable substitution Fix: $eval ls $pipe wc l #will work as expected #The first time, the shell scans the line and substitutes as the value of the pipe. Then the command line is rescanned at which point the pipe is recognized. Exercise: How do you print the last argument given to a program? 32

33 In-line Input Redirection Command << endingword #The shell will use the lines from the stdin as the input to the command until a line with endingword Example: $ wc -l <<TheEnd > Hi > This is a test > TheEnd 2 33

34 Shell Archives One or more related shell programs can be put into a single file and shipped to a username with a mail command. The shipped file can be unpacked by running the shell on it. Example: An archive file called shellprogs is created using the shell script, shellarchive The file shellprogs contains two shell scripts lookup and countwords. The file shellprogs is mailed to a username. The user unpacks the file shellprogs by running the shell on it resulting in the files, lookup and countwords 34

35 $ cat shellprogs echo "Extracting script lookup" cat >lookup <<\END_OF_DATA name=$1 grep "$name" $PHONEBOOK if [ $? -ne 0 ] then echo "Name is not in the phone book" fi END_OF_DATA echo "Extracting script countwords" cat >countwords <<\END_OF_DATA read line set $line echo "NoOfWOrds = $#" END_OF_DATA 35

36 $cat shellarchive # Creates a shell archive from a set of files. The filenames are given as # command line arguments For file do done echo echo echo extracting script $file echo cat >$file <<\END_OF_DATA cat $file echo END_OF_DATA 36

37 Grouping Commands The semicolon allows users to string commands together on a single line as if one command was being issued. Each command within the semicolon separated list is executed by the shell in succession. Example: $ cd /user/jsmith; make The parentheses, when grouped around a command, cause the command to be executed in a sub-shell. Example: $ cd ; ls #change to the home directory and list the contents $ cprogs shellprogs # contents of the home directory $ (cd cprogs ; ls ); ls a.c b.c x.c #contents of cprogs cprogs shellprogs #contents of home directory 37

38 Grouping commands Examples: $ line=hi $(line=bye) #execute it in a subshell $echo $line #hi $ { line=bye; } #execute it in the current shell $echo $line #bye 38

39 Parameter Substitution Parameter substitution is a method of providing a default value for a variable in the event that it is currently null. The construct uses a combination of braces delimiting a variable and its default. The variable and default value are separated by a keyword. The keyword serves as a condition for when to assign the value to the variable. Supposing a script tries to de-reference a null variable, a good programmer can avoid catastrophic errors by using parameter substitution: 39

40 Examples: ${parameter} - Substitute the value of parameter. file=prog1 cp $file $filea # intention is to copy prog1 into prog1a.# Will not work since filea will be treated as a variable cp $file ${file}a 40

41 ${parameter:-value} - Substitute the value of parameter if it is not null; otherwise, use value. $ result=1 $ echo "result is ${result:-2}" result is 1 $ result= $ echo "result is ${result:-2} #the value can be a backquoted command result is 2 $ echo "$result" 41

42 ${parameter:=value} Substitute the value of parameter if it is not null; otherwise, use value and also assign value to parameter. Example: $ result= $ echo "result is ${result:=2}" result is 2 $ echo "$result" 2 42

43 ${parameter:?value} Substitute the value of parameter if it is not null; otherwise, write value to standard error and exit. If value is omitted, then write "parameter: parameter null or not set" instead. Example: result= $ echo "result is ${result:?}" sh: result: Parameter null or not set. $ echo "result is ${result:? result set now } 43

44 ${parameter:+value} Substitute value if parameter is not null; otherwise, substitute nothing. Example: $ tracing=t $ echo "tracing is ${tracing:+on}" tracing is on 44

45 exec The exec built-in command spawns its arguments into a new process and runs it in place of the currently running process. Example if [ "${MYSCRIPT}" = "" ] then exit else fi if [ -x ${MYSCRIPT} ] then fi echo "Executing ${MYSCRIPT}" exec ${MYSCRIPT} 45

46 Synchronizing tasks Since UNIX offers multitasking, commands can be sent to the background so that they are executed when the kernel finds time. After a command is sent to the background, the shell frees itself to handle other commands. To background a command, the user appends an ampersand, &, to it. Example: $ find / -name junkfile.tar print 2>/dev/null & [1] #process id is printed by the shell $date #handle another command Wed Jun 21 08:46:58 PDT

47 wait Sometimes it may be necessary to synchronize a script with an asynchronous process, ie. a backgrounded job. Wait is a built-in command for such synchronization. Wait takes an optional process number as its argument and pauses the shell's execution until the specified process had terminated. If only one process has been sent to the background, then wait can be issued without an argument. It will automatically wait for the job to complete. If more than one job is running in the background Wait $! # waits for the last process that is sent to the background process identifiers can be stored in variables and passed to wait to specify the job to be waited for. 47

48 wait Examples: $ find / -name junkfile.tar print 2>/dev/null & [1] #process id is printed by the shell $ Wait $processcmd1 & $pid1=$! $processcmd2 & $pid2=$! wait $pid1 wait $pid2 48

49 trap The pressing of DELETE key at the terminal, when a program is in execution, sends a signal to the executing program. Using the trap command, the program can specify the action to be taken on receiving the signal. Usage: trap commands signals, where commands are the actions to be taken on receiving the signals. Some Commonly used signal numbers 0 Exit from Shell 1 Hangup 2 Interrupt (eg: Delete key) 15 Software termination (sent by kill, for example) 49

50 Example Example: #!/bin/sh i=1 JUNK=junkfile trap rm $JUNK$$;exit 2 while [ $i -le 100 ] Do # remove the file when interrupt is received echo $i >> $JUNK$$ i=`expr $i + 1` done 50

51 More On I/O The shell permits the combination of the basic I/O constructs with a file descriptor. A file descriptor (also known as a file handle) is a non-negative digit that points at a file. The file descriptors for stdin, stdout, and stderr are 0, 1, and 2, respectively. Any of these may be redirected to a file or to each other. In other words, it is quite possible to send the output from stdin and stderr to the same file. This is quite useful when a user would rather check a script's results after it has completed processing. Examples command 2> file redirects the standard error from any command cd JUNK 2>>out #the directory JUNK does not exist cat out sh: JUNK: not found. $ cd JUNK >>out 2>&1 #Change directory to JUNK, redirect stdout to the file out, and then redirect stderr to the same file that stdout uses." $ cat out sh: JUNK: not found. 51

52 Functions The Bourne shell allows the grouping of commands into a reusable instruction set called a function. Functions have two parts: a label and a body. The label names the function and is used to invoke the function. Some rules in declaring a function: 1. The function label must be unique; it cannot be the same as any other variable or other function. 2. An empty set of parentheses must always follow the function label. They instruct the shell that a function is being defined. 3. Braces, {}, must be used to delimit the function's body. 4. A function must be defined before it can be used in a script. 52

53 $cat fun_example1 #!/bin/sh setenvironment () { } ROOT=${PWD} LIB=${ROOT}/proglib BIN=${ROOT}/bin Functions echo "Trying to print environment..." echo ${ROOT} ${LIB} ${BIN} #invoking the function setenvironment echo "Trying to print environment again..." echo ${ROOT} ${LIB} ${BIN} 53

54 $fun_example1 #output Trying to print environment... Trying to print environment again... /proglib /bin 54

55 cat fun_example2 #!/bin/sh setenvironment () { } ROOT=${1} LIB=${ROOT}/proglib BIN=${ROOT}/bin Functions with arguments echo "Trying to print environment..." echo ${ROOT} ${LIB} ${BIN} #invoking setenvironment with an argument setenvironment./demos echo "Trying to print environment again..." echo ${ROOT} ${LIB} ${BIN} 55

56 $fun_example2 #output Trying to print environment... Trying to print environment again..../demos./demos/proglib./demos/bin 56

57 Returning a value Functions return the exit status of the last command executed. it uses the status of the last command issued. A script controls its exit status by issuing an exit with a nonnegative value. On the other hand, functions do not use exit because it is designed to terminate the shell. Instead, functions use return. The return command stops execution of a function returning program control to the point in the script where the function was called. Script execution continues from where the function was invoked. The format of return follows return n where n is any non-negative integer. Providing a return value is optional just as providing a status code to exit is optional. If no code is given, return defaults to the value returned by the last command executed. 57

58 Functions returning a value $cat fun_example3 #!/bin/sh isadir() { if [! -d ${1} ] then return 1 fi } isadir demos echo $? isadir fun2 echo $? 58

59 Functions $cat fun_example4 #!/bin/sh isadir() { if [! -d ${1} ] then return 1 fi } #Functions can be embedded in a test if [ "isadir ${HOME}" ] then echo "Yes $HOME is a directory" fi 59

60 Changes made in functions Changes made to variables persist beyond execution of the function. Cat fun_example5 #!/bin/sh change(){ ONE="Bye" ONE="Hi" TWO="NewVal"} echo "ONE = ${ONE}" echo "TWO = ${TWO}" change echo "ONE = ${ONE}" echo "TWO = ${TWO}" 60

61 $fun_example5 #output changesinfun ONE = Bye TWO = ONE = Hi TWO = NewVal 61

62 Including functions in multiple scripts % cat printdata #!/bin/sh printarg () { echo ${1} echo } cat counteruser #!/bin/sh # execute the file printdata in the # current shell. This will cause any functions # defined inside the file printdata to be read in # and defined In the current shell.. printdata x=0 while [ ${x} -le 10 ] do #calling function printdata printarg $x x=`expr ${x} + 1` done echo "Done" 62

63 Functions Functions are a very useful tool to allow scripters to organize actions into logical blocks. It is easier to think of a program a series of steps to perform and then to expand those steps into functions that perform the necessary actions. This is much better than trying to list every single command in order. In addition, functions can improve a script's performance. Rather than employ functions, you might consider grouping logical blocks into subscripts which the main script uses. This technique will work just fine, but the program's execution time will take a hit. When a script calls a subscript, the shell must find the subscript on disk, open it, read it into memory, and then execute it. This process happens every time a subscript is called even though the subscript may have been used previously. Functions are read once into memory as soon as they are declared. They have the advantage of one time read for multiple execution. 63

64 Some Environment Variables PS1- stores the command prompt PS2 stores the secondary command prompt HOME Stores the home directory PATH contains a list of directories which the shell searches whenever you type in the name of the program to be executed. The PATH specifies the directories to be searched for programs to be executed and not for any other types of files. $ echo $PATH displays output which may look like this /bin:/usr/bin:: CDPATH 64

65 The.profile file At the end of the login sequence, the login shell executes two special files - /etc/profile and.profile in your home directory. /etc/profile set up by the SysAdmin and does the tasks that the administrator wants to execute when you log in (eg: checking if you have mail).profile (you will get a default.profile when you get your account): gets automatically gets executed when you log in. You can include any commands that you want executed whenever you login. Example: PATH=/bin:/usr/bin:/$HOME/bin:: CDPATH=:$HOME:$HOME/progs PS1= => PS2= = export PATH CDPATH PS1 PS2 65

COMP 4/6262: Programming UNIX

COMP 4/6262: Programming UNIX COMP 4/6262: Programming UNIX Lecture 12 shells, shell programming: passing arguments, if, debug March 13, 2006 Outline shells shell programming passing arguments (KW Ch.7) exit status if (KW Ch.8) test

More information

Bourne Shell Reference

Bourne Shell Reference > Linux Reviews > Beginners: Learn Linux > Bourne Shell Reference Bourne Shell Reference found at Br. David Carlson, O.S.B. pages, cis.stvincent.edu/carlsond/cs330/unix/bshellref - Converted to txt2tags

More information

Assignment clarifications

Assignment clarifications Assignment clarifications How many errors to print? at most 1 per token. Interpretation of white space in { } treat as a valid extension, involving white space characters. Assignment FAQs have been updated.

More information

A shell can be used in one of two ways:

A shell can be used in one of two ways: Shell Scripting 1 A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) 2 If we have a set of commands

More information

Unix Scripts and Job Scheduling. Overview. Running a Shell Script

Unix Scripts and Job Scheduling. Overview. Running a Shell Script Unix Scripts and Job Scheduling Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring Overview Shell Scripts

More information

5/20/2007. Touring Essential Programs

5/20/2007. Touring Essential Programs Touring Essential Programs Employing fundamental utilities. Managing input and output. Using special characters in the command-line. Managing user environment. Surveying elements of a functioning system.

More information

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012 Cisco IOS Shell Last Updated: December 14, 2012 The Cisco IOS Shell (IOS.sh) feature provides shell scripting capability to the Cisco IOS command-lineinterface (CLI) environment. Cisco IOS.sh enhances

More information

Linux shell programming for Raspberry Pi Users - 2

Linux shell programming for Raspberry Pi Users - 2 Linux shell programming for Raspberry Pi Users - 2 Sarwan Singh Assistant Director(S) NIELIT Chandigarh 1 SarwanSingh.com Education is the kindling of a flame, not the filling of a vessel. - Socrates SHELL

More information

Useful Unix Commands Cheat Sheet

Useful Unix Commands Cheat Sheet Useful Unix Commands Cheat Sheet The Chinese University of Hong Kong SIGSC Training (Fall 2016) FILE AND DIRECTORY pwd Return path to current directory. ls List directories and files here. ls dir List

More information

bash, part 3 Chris GauthierDickey

bash, part 3 Chris GauthierDickey bash, part 3 Chris GauthierDickey More redirection As you know, by default we have 3 standard streams: input, output, error How do we redirect more than one stream? This requires an introduction to file

More information

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell. Command Interpreters A command interpreter is a program that executes other programs. Aim: allow users to execute the commands provided on a computer system. Command interpreters come in two flavours:

More information

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1 Shell Scripting Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 If we have a set of commands that we want to run on a regular basis, we could write a script A script acts as a Linux command,

More information

Shells and Shell Programming

Shells and Shell Programming Shells and Shell Programming 1 Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed

More information

Bash Programming. Student Workbook

Bash Programming. Student Workbook Student Workbook Bash Programming Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112 Contributing Authors: Julie Johnson, Rob Roselius Editor: Jeff Howell Special

More information

There are some string operators that can be used in the test statement to perform string comparison.

There are some string operators that can be used in the test statement to perform string comparison. ACS-294- Unix (Winter Term, 26-7) Part II: Shell Programming Page 3 The test also returns a nonzero exit value if there is no argument: test String Operators There are some string operators that can be

More information

Basic Linux (Bash) Commands

Basic Linux (Bash) Commands Basic Linux (Bash) Commands Hint: Run commands in the emacs shell (emacs -nw, then M-x shell) instead of the terminal. It eases searching for and revising commands and navigating and copying-and-pasting

More information

Shells and Shell Programming

Shells and Shell Programming Shells and Shell Programming Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed

More information

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Essentials for Scientific Computing: Bash Shell Scripting Day 3 Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash

More information

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 Bashed One Too Many Times Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 What is a Shell? The shell interprets commands and executes them It provides you with an environment

More information

Shells & Shell Programming (Part B)

Shells & Shell Programming (Part B) Shells & Shell Programming (Part B) Software Tools EECS2031 Winter 2018 Manos Papagelis Thanks to Karen Reid and Alan J Rosenthal for material in these slides CONTROL STATEMENTS 2 Control Statements Conditional

More information

BASH and command line utilities Variables Conditional Commands Loop Commands BASH scripts

BASH and command line utilities Variables Conditional Commands Loop Commands BASH scripts BASH and command line utilities Variables Conditional Commands Loop Commands BASH scripts SCOMRED, October 2018 Instituto Superior de Engenharia do Porto (ISEP) Departamento de Engenharia Informática(DEI)

More information

Processes and Shells

Processes and Shells Shell ls pico httpd CPU Kernel Disk NIC Processes Processes are tasks run by you or the OS. Processes can be: shells commands programs daemons scripts Shells Processes operate in the context of a shell.

More information

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs Summer 2010 Department of Computer Science and Engineering York University Toronto June 29, 2010 1 / 36 Table of contents 1 2 3 4 2 / 36 Our goal Our goal is to see how we can use Unix as a tool for developing

More information

Shell Scripting. With Applications to HPC. Edmund Sumbar Copyright 2007 University of Alberta. All rights reserved

Shell Scripting. With Applications to HPC. Edmund Sumbar Copyright 2007 University of Alberta. All rights reserved AICT High Performance Computing Workshop With Applications to HPC Edmund Sumbar research.support@ualberta.ca Copyright 2007 University of Alberta. All rights reserved High performance computing environment

More information

85321, Systems Administration Chapter 6: The shell

85321, Systems Administration Chapter 6: The shell Chapter 6 Introduction The Shell You will hear many people complain that the UNIX operating system is hard to use. They are wrong. What they actually mean to say is that the UNIX command line interface

More information

Conditional Control Structures. Dr.T.Logeswari

Conditional Control Structures. Dr.T.Logeswari Conditional Control Structures Dr.T.Logeswari TEST COMMAND test expression Or [ expression ] Syntax Ex: a=5; b=10 test $a eq $b ; echo $? [ $a eq $b] ; echo $? 2 Unix Shell Programming - Forouzan 2 TEST

More information

UNIX Shell Programming

UNIX Shell Programming $!... 5:13 $$ and $!... 5:13.profile File... 7:4 /etc/bashrc... 10:13 /etc/profile... 10:12 /etc/profile File... 7:5 ~/.bash_login... 10:15 ~/.bash_logout... 10:18 ~/.bash_profile... 10:14 ~/.bashrc...

More information

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong Shell Prof. Jinkyu Jeong (Jinkyu@skku.edu) TA -- Minwoo Ahn (minwoo.ahn@csl.skku.edu) TA -- Donghyun Kim (donghyun.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

More information

CS Unix Tools & Scripting

CS Unix Tools & Scripting Cornell University, Spring 2014 1 February 24, 2014 1 Slides evolved from previous versions by Hussam Abu-Libdeh and David Slater A note on awk for (item in array) The order in which items are returned

More information

Shell programming. Introduction to Operating Systems

Shell programming. Introduction to Operating Systems Shell programming Introduction to Operating Systems Environment variables Predened variables $* all parameters $# number of parameters $? result of last command $$ process identier $i parameter number

More information

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow

More information

Appendix A GLOSSARY. SYS-ED/ Computer Education Techniques, Inc.

Appendix A GLOSSARY. SYS-ED/ Computer Education Techniques, Inc. Appendix A GLOSSARY SYS-ED/ Computer Education Techniques, Inc. $# Number of arguments passed to a script. $@ Holds the arguments; unlike $* it has the capability for separating the arguments. $* Holds

More information

UNIX shell scripting

UNIX shell scripting UNIX shell scripting EECS 2031 Summer 2014 Przemyslaw Pawluk June 17, 2014 What we will discuss today Introduction Control Structures User Input Homework Table of Contents Introduction Control Structures

More information

Linux shell scripting Getting started *

Linux shell scripting Getting started * Linux shell scripting Getting started * David Morgan *based on chapter by the same name in Classic Shell Scripting by Robbins and Beebe What s s a script? text file containing commands executed as a unit

More information

While Statement Examples. While Statement (35.15) Until Statement (35.15) Until Statement Example

While Statement Examples. While Statement (35.15) Until Statement (35.15) Until Statement Example While Statement (35.15) General form. The commands in the loop are performed while the condition is true. while condition one-or-more-commands While Statement Examples # process commands until a stop is

More information

Shell Programming (bash)

Shell Programming (bash) Shell Programming Shell Programming (bash) Commands run from a file in a subshell A great way to automate a repeated sequence of commands. File starts with #!/bin/bash absolute path to the shell program

More information

EECS2301. Example. Testing 3/22/2017. Linux/Unix Part 3. for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done

EECS2301. Example. Testing 3/22/2017. Linux/Unix Part 3. for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala Introduction to Linux Basics Part II 1 Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala pakala@uga.edu 2 Variables in Shell HOW DOES LINUX WORK? Shell Arithmetic I/O and

More information

UNIX System Programming Lecture 3: BASH Programming

UNIX System Programming Lecture 3: BASH Programming UNIX System Programming Outline Filesystems Redirection Shell Programming Reference BLP: Chapter 2 BFAQ: Bash FAQ BMAN: Bash man page BPRI: Bash Programming Introduction BABS: Advanced Bash Scripting Guide

More information

Basics. I think that the later is better.

Basics.  I think that the later is better. Basics Before we take up shell scripting, let s review some of the basic features and syntax of the shell, specifically the major shells in the sh lineage. Command Editing If you like vi, put your shell

More information

Last Time. on the website

Last Time. on the website Last Time on the website Lecture 6 Shell Scripting What is a shell? The user interface to the operating system Functionality: Execute other programs Manage files Manage processes Full programming language

More information

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017 bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017 Positional Arguments It is quite common to allow the user of a script to specify what the script is to operate on (e.g. a

More information

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

Advanced Unix Programming Module 03 Raju Alluri spurthi.com Advanced Unix Programming Module 03 Raju Alluri askraju @ spurthi.com Advanced Unix Programming: Module 3 Shells & Shell Programming Environment Variables Writing Simple Shell Programs (shell scripts)

More information

Vi & Shell Scripting

Vi & Shell Scripting Vi & Shell Scripting Comp-206 : Introduction to Week 3 Joseph Vybihal Computer Science McGill University Announcements Sina Meraji's office hours Trottier 3rd floor open area Tuesday 1:30 2:30 PM Thursday

More information

UNIX Shell Scripts. What Is a Shell? The Bourne Shell. Executable Files. Executable Files: Example. Executable Files (cont.) CSE 2031 Fall 2012

UNIX Shell Scripts. What Is a Shell? The Bourne Shell. Executable Files. Executable Files: Example. Executable Files (cont.) CSE 2031 Fall 2012 What Is a Shell? UNIX Shell Scripts CSE 2031 Fall 2012 A program that interprets your requests to run other programs Most common Unix shells: Bourne shell (sh) C shell (csh - tcsh) Korn shell (ksh) Bourne-again

More information

Introduction to UNIX Part II

Introduction to UNIX Part II T H E U N I V E R S I T Y of T E X A S H E A L T H S C I E N C E C E N T E R A T H O U S T O N S C H O O L of H E A L T H I N F O R M A T I O N S C I E N C E S Introduction to UNIX Part II For students

More information

Computer Systems and Architecture

Computer Systems and Architecture Computer Systems and Architecture UNIX Scripting Bart Meyers University of Antwerp August 29, 2012 Outline Basics Conditionals Loops Advanced Exercises Shell scripts Grouping commands into a single file

More information

Програмиранев UNIX среда

Програмиранев UNIX среда Програмиранев UNIX среда Използванена команден шел и създаванена скриптове: tcsh, bash, awk, python Shell programming As well as using the shell to run commands you can use its built-in programming language

More information

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash CS 25200: Systems Programming Lecture 10: Shell Scripting in Bash Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Lecture 10 Getting started with Bash Data types Reading and writing Control loops Decision

More information

Essential Unix (and Linux) for the Oracle DBA. Revision no.: PPT/2K403/02

Essential Unix (and Linux) for the Oracle DBA. Revision no.: PPT/2K403/02 Essential Unix (and Linux) for the Oracle DBA Revision no.: PPT/2K403/02 Architecture of UNIX Systems 2 UNIX System Structure 3 Operating system interacts directly with Hardware Provides common services

More information

Scripting. More Shell Scripts Loops. Adapted from Practical Unix and Programming Hunter College

Scripting. More Shell Scripts Loops. Adapted from Practical Unix and Programming Hunter College Scripting More Shell Scripts Loops Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss Loops: for The for script version 1: 1 #!/bin/bash 2 for i in 1 2 3 3 do

More information

Chapter 9. Shell and Kernel

Chapter 9. Shell and Kernel Chapter 9 Linux Shell 1 Shell and Kernel Shell and desktop enviroment provide user interface 2 1 Shell Shell is a Unix term for the interactive user interface with an operating system A shell usually implies

More information

Shell script. Shell Scripts. A shell script contains a sequence of commands in a text file. Shell is an command language interpreter.

Shell script. Shell Scripts. A shell script contains a sequence of commands in a text file. Shell is an command language interpreter. Shell Scripts A shell script contains a sequence of commands in a text file. Shell is an command language interpreter. Shell executes commands read from a file. Shell is a powerful programming available

More information

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT Unix as a Platform Exercises + Solutions Course Code: OS 01 UNXPLAT Working with Unix Most if not all of these will require some investigation in the man pages. That's the idea, to get them used to looking

More information

Introduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi

Introduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi Bash Scripting Alessandro Barenghi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano alessandro.barenghi - at - polimi.it April 28, 2015 Introduction The bash command shell

More information

Review of Fundamentals

Review of Fundamentals Review of Fundamentals 1 The shell vi General shell review 2 http://teaching.idallen.com/cst8207/14f/notes/120_shell_basics.html The shell is a program that is executed for us automatically when we log

More information

EECS 470 Lab 5. Linux Shell Scripting. Friday, 1 st February, 2018

EECS 470 Lab 5. Linux Shell Scripting. Friday, 1 st February, 2018 EECS 470 Lab 5 Linux Shell Scripting Department of Electrical Engineering and Computer Science College of Engineering University of Michigan Friday, 1 st February, 2018 (University of Michigan) Lab 5:

More information

INTRODUCTION TO SHELL SCRIPTING ITPART 2

INTRODUCTION TO SHELL SCRIPTING ITPART 2 INTRODUCTION TO SHELL SCRIPTING ITPART 2 Dr. Jeffrey Frey University of Delaware, version 2 GOALS PART 2 Shell plumbing review Standard files Redirection Pipes GOALS PART 2 Command substitution backticks

More information

Shell Script Example. Here is a hello world shell script: $ ls -l -rwxr-xr-x 1 horner 48 Feb 19 11:50 hello* $ cat hello #!/bin/sh

Shell Script Example. Here is a hello world shell script: $ ls -l -rwxr-xr-x 1 horner 48 Feb 19 11:50 hello* $ cat hello #!/bin/sh Shell Programming Shells A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) Shell Scripts A shell

More information

Introduction to Bash Programming. Dr. Xiaolan Zhang Spring 2013 Dept. of Computer & Information Sciences Fordham University

Introduction to Bash Programming. Dr. Xiaolan Zhang Spring 2013 Dept. of Computer & Information Sciences Fordham University Introduction to Bash Programming Dr. Xiaolan Zhang Spring 2013 Dept. of Computer & Information Sciences Fordham University 1 Outline Shell command line syntax Shell builtin commands Shell variables, arguments

More information

QUESTION BANK ON UNIX & SHELL PROGRAMMING-502 (CORE PAPER-2)

QUESTION BANK ON UNIX & SHELL PROGRAMMING-502 (CORE PAPER-2) BANK ON & SHELL PROGRAMMING-502 (CORE PAPER-2) TOPIC 1: VI-EDITOR MARKS YEAR 1. Explain set command of vi editor 2 2011oct 2. Explain the modes of vi editor. 7 2013mar/ 2013 oct 3. Explain vi editor 5

More information

The Unix Shell & Shell Scripts

The Unix Shell & Shell Scripts The Unix Shell & Shell Scripts You should do steps 1 to 7 before going to the lab. Use the Linux system you installed in the previous lab. In the lab do step 8, the TA may give you additional exercises

More information

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017 Linux Shell Scripting Linux System Administration COMP2018 Summer 2017 What is Scripting? Commands can be given to a computer by entering them into a command interpreter program, commonly called a shell

More information

Linux Bash Shell Scripting

Linux Bash Shell Scripting University of Chicago Initiative in Biomedical Informatics Computation Institute Linux Bash Shell Scripting Present by: Mohammad Reza Gerami gerami@ipm.ir Day 2 Outline Support Review of Day 1 exercise

More information

Log into Linux Reminders: Homework 1 due today; Homework 2 due on Thursday Questions?

Log into Linux Reminders: Homework 1 due today; Homework 2 due on Thursday Questions? Lecture 4 Log into Linux Reminders: Homework 1 due today; Homework 2 due on Thursday Questions? Tuesday, September 8 CS 375 UNIX System Programming - Lecture 4 1 Outline Exercise from last lecture More

More information

Shell Control Structures

Shell Control Structures Shell Control Structures EECS 2031 20 November 2017 1 Control Structures l if else l for l while l case (which) l until 2 1 if Statement and test Command l Syntax: if condition command(s) elif condition_2

More information

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP Unix Guide Meher Krishna Patel Created on : Octorber, 2017 Last updated : December, 2017 More documents are freely available at PythonDSP Table of contents Table of contents i 1 Unix commands 1 1.1 Unix

More information

Title:[ Variables Comparison Operators If Else Statements ]

Title:[ Variables Comparison Operators If Else Statements ] [Color Codes] Environmental Variables: PATH What is path? PATH=$PATH:/MyFolder/YourStuff?Scripts ENV HOME PWD SHELL PS1 EDITOR Showing default text editor #!/bin/bash a=375 hello=$a #No space permitted

More information

CSC UNIX System, Spring 2015

CSC UNIX System, Spring 2015 CSC 352 - UNIX System, Spring 2015 Study guide for the CSC352 midterm exam (20% of grade). Dr. Dale E. Parson, http://faculty.kutztown.edu/parson We will have a midterm on March 19 on material we have

More information

Shell Programming. Introduction to Linux. Peter Ruprecht Research CU Boulder

Shell Programming. Introduction to Linux. Peter Ruprecht  Research CU Boulder Introduction to Linux Shell Programming Peter Ruprecht peter.ruprecht@colorado.edu www.rc.colorado.edu Downloadable Materials Slides and examples available at https://github.com/researchcomputing/ Final_Tutorials/

More information

CSCI 211 UNIX Lab. Shell Programming. Dr. Jiang Li. Jiang Li, Ph.D. Department of Computer Science

CSCI 211 UNIX Lab. Shell Programming. Dr. Jiang Li. Jiang Li, Ph.D. Department of Computer Science CSCI 211 UNIX Lab Shell Programming Dr. Jiang Li Why Shell Scripting Saves a lot of typing A shell script can run many commands at once A shell script can repeatedly run commands Help avoid mistakes Once

More information

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2018

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2018 bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2018 Error Output Failed commands often generate unwanted or irrelevant error messages That output can be saved as a log, sent

More information

Basic UNIX Commands BASIC UNIX COMMANDS. 1. cat command. This command is used to create a file in unix. Syntax: $ cat filename

Basic UNIX Commands BASIC UNIX COMMANDS. 1. cat command. This command is used to create a file in unix. Syntax: $ cat filename Basic UNIX Commands BASIC UNIX COMMANDS 1. cat This is used to create a file in unix. $ cat >filename This is also used for displaying contents in a file. $ cat filename 2. ls It displays the list of files

More information

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017 bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017 Command Lists A command is a sequence of commands separated by the operators ; & && and ; is used to simply execute commands in

More information

Implementation of a simple shell, xssh

Implementation of a simple shell, xssh Implementation of a simple shell, xssh What is a shell? A process that does command line interpretation Reads a command from standard input (stdin) Executes command corresponding to input line In simple

More information

Creating a Shell or Command Interperter Program CSCI411 Lab

Creating a Shell or Command Interperter Program CSCI411 Lab Creating a Shell or Command Interperter Program CSCI411 Lab Adapted from Linux Kernel Projects by Gary Nutt and Operating Systems by Tannenbaum Exercise Goal: You will learn how to write a LINUX shell

More information

Consider the following program.

Consider the following program. Consider the following program. #include int do_sth (char *s); main(){ char arr [] = "We are the World"; printf ("%d\n", do_sth(arr)); } int do_sth(char *s) { char *p = s; while ( *s++!= \0 )

More information

example: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable.

example: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable. Bourne Shell Programming Variables - creating and assigning variables Bourne shell use the set and unset to create and assign values to variables or typing the variable name, an equal sign and the value

More information

Introduction to UNIX. Introduction. Processes. ps command. The File System. Directory Structure. UNIX is an operating system (OS).

Introduction to UNIX. Introduction. Processes. ps command. The File System. Directory Structure. UNIX is an operating system (OS). Introduction Introduction to UNIX CSE 2031 Fall 2012 UNIX is an operating system (OS). Our goals: Learn how to use UNIX OS. Use UNIX tools for developing programs/ software, specifically shell programming.

More information

Introduction to UNIX. CSE 2031 Fall November 5, 2012

Introduction to UNIX. CSE 2031 Fall November 5, 2012 Introduction to UNIX CSE 2031 Fall 2012 November 5, 2012 Introduction UNIX is an operating system (OS). Our goals: Learn how to use UNIX OS. Use UNIX tools for developing programs/ software, specifically

More information

Computer Systems and Architecture

Computer Systems and Architecture Computer Systems and Architecture Stephen Pauwels UNIX Scripting Academic Year 2018-2019 Outline Basics Conditionals Loops Advanced Exercises Shell Scripts Grouping commands into a single file Reusability

More information

Introduction to the Shell

Introduction to the Shell [Software Development] Introduction to the Shell Davide Balzarotti Eurecom Sophia Antipolis, France What a Linux Desktop Installation looks like What you need Few Words about the Graphic Interface Unlike

More information

Shell Programming Overview

Shell Programming Overview Overview Shell programming is a way of taking several command line instructions that you would use in a Unix command prompt and incorporating them into one program. There are many versions of Unix. Some

More information

LOG ON TO LINUX AND LOG OFF

LOG ON TO LINUX AND LOG OFF EXPNO:1A LOG ON TO LINUX AND LOG OFF AIM: To know how to logon to Linux and logoff. PROCEDURE: Logon: To logon to the Linux system, we have to enter the correct username and password details, when asked,

More information

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019 CSCI 2132: Software Development Shell Scripting Norbert Zeh Faculty of Computer Science Dalhousie University Winter 2019 Reading Glass and Ables, Chapter 8: bash Your Shell vs Your File Manager File manager

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs. CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs

More information

System Programming. Introduction to Unix

System Programming. Introduction to Unix Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Introduction 2 3 Introduction

More information

Unix/Linux Basics. Cpt S 223, Fall 2007 Copyright: Washington State University

Unix/Linux Basics. Cpt S 223, Fall 2007 Copyright: Washington State University Unix/Linux Basics 1 Some basics to remember Everything is case sensitive Eg., you can have two different files of the same name but different case in the same folder Console-driven (same as terminal )

More information

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions?

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions? Lecture 4 Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions? Tuesday, September 7 CS 375 UNIX System Programming - Lecture

More information

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND Prof. Michael J. Reale Fall 2014 Finding Files in a Directory Tree Suppose you want to find a file with a certain filename (or with a filename matching

More information

12.1 UNDERSTANDING UNIX SHELL PROGRAMMING LANGUAGE: AN INTRODUCTION Writing a Simple Script Executing a Script

12.1 UNDERSTANDING UNIX SHELL PROGRAMMING LANGUAGE: AN INTRODUCTION Writing a Simple Script Executing a Script 12 Shell Programming This chapter concentrates on shell programming. It explains the capabilities of the shell as an interpretive high-level language. It describes shell programming constructs and particulars.

More information

Unix as a Platform Exercises. Course Code: OS-01-UNXPLAT

Unix as a Platform Exercises. Course Code: OS-01-UNXPLAT Unix as a Platform Exercises Course Code: OS-01-UNXPLAT Working with Unix 1. Use the on-line manual page to determine the option for cat, which causes nonprintable characters to be displayed. Run the command

More information

5/8/2012. Exploring Utilities Chapter 5

5/8/2012. Exploring Utilities Chapter 5 Exploring Utilities Chapter 5 Examining the contents of files. Working with the cut and paste feature. Formatting output with the column utility. Searching for lines containing a target string with grep.

More information

Shell scripting Scripting and Computer Environment - Lecture 5

Shell scripting Scripting and Computer Environment - Lecture 5 Shell scripting Scripting and Computer Environment - Lecture 5 Saurabh Barjatiya International Institute Of Information Technology, Hyderabad 28 July, 2011 Contents 1 Contents 1 Shell scripting with bash

More information

22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University

22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University Lecture 8 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control 22-Sep-2017 Location: Goldberg CS 127 Time: 14:35 15:25 Instructor:

More information

LING 408/508: Computational Techniques for Linguists. Lecture 5

LING 408/508: Computational Techniques for Linguists. Lecture 5 LING 408/508: Computational Techniques for Linguists Lecture 5 Last Time Installing Ubuntu 18.04 LTS on top of VirtualBox Your Homework 2: did everyone succeed? Ubuntu VirtualBox Host OS: MacOS or Windows

More information

Chapter 5 The Bourne Shell

Chapter 5 The Bourne Shell Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, 2003 Notes by Bing Li Creating/Assigning a Variable Name=value Variable created

More information

Bash shell programming Part II Control statements

Bash shell programming Part II Control statements Bash shell programming Part II Control statements Deniz Savas and Michael Griffiths 2005-2011 Corporate Information and Computing Services The University of Sheffield Email M.Griffiths@sheffield.ac.uk

More information

The UNIX Shells. Computer Center, CS, NCTU. How shell works. Unix shells. Fetch command Analyze Execute

The UNIX Shells. Computer Center, CS, NCTU. How shell works. Unix shells. Fetch command Analyze Execute Shells The UNIX Shells How shell works Fetch command Analyze Execute Unix shells Shell Originator System Name Prompt Bourne Shell S. R. Bourne /bin/sh $ Csh Bill Joy /bin/csh % Tcsh Ken Greer /bin/tcsh

More information