Presentation is loading. Please wait.

Presentation is loading. Please wait.

The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between.

Similar presentations


Presentation on theme: "The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between."— Presentation transcript:

1

2 The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between the then and if are executed, otherwise they are skipped if command then command … fi

3 exit status Whenever any program completes execution, it returns an exit status back to the system status is a number status 0: program executed successfully status of nonzero: program executed unsuccessfully

4 The $? Variable The shell variable $? Is automatically set by the shell to the exit status of the last command executed

5 The $? Variable (continue.) $ touch file1 $ cp file1 file2 $ echo $? 0 $ cp file3 file1 cp: cannot access file3 $ who hyunku console Jan 24 00:16 (:0) hyunku pts/4 Jan 24 00:16 (:0.0) sbenayed pts/5 Jan 251 12:01 (216.87.102.199) $ who | grep abuzneid $ echo $? 1 $ who | grep sbenayed sbenayed pts/5 Jan 25 21:01 (216.87.102.199) $ echo $? 0

6 The test command Format: test expression test evaluates expression, and if the result is true, it returns an exit status of zero, otherwise the result is false test "$name" = Alice Operator (=) separates arguments which means it must be surrounded with white space characters It's a good programming practice to enclose shell variables that are arguments to test inside a pair of doubles quotes

7 The test command (continue.) = Alice test arguments $ name= $ test $name = Alice test: argument expected $ test "$name" = Alice $ test $name = Alice without name null

8 The test command (continue.) = null Alice test arguments test $name = Alice with name null

9 File operators in test command OperatorReturns TRUE (zero exit status) if -b filefile is a block special file -c filefile is a character special file -d filefile is a directory -f filefile is an ordinary -g filefile has its set group id (SGID) bit set -k filefile has its sticky bit set -p filefile is a named pipe

10 File operators in test command (continue.) OperatorReturns TRUE (zero exit status) if -r filefile is readable by the process -s filefile has nonzero length -t filefile is open file descriptor associated with a terminal (1 is default) -u filefile has its set user id (SUID) bit set -w filefile is writable by the process -x filefile is executable

11 String operators in test command (continue.) OperatorReturns TRUE (zero exit status) if stringstring is not null -n stringstring is not null (and string must be seen by test) -z stringstring is null (and string must be seen by test) String 1 = string 2 string 1 is identical to string 2 string 1 ! = string 2 string 1 is not identical to string 2

12 Integer Comparison Operators in test command (continue.) OperatorReturns TRUE (zero exit status) if int 1 – eq int 2 int 1 is equal to int 2 int 1 – ge int 2 int 1 is greater than or equal to int 2 int 1 – gt int 2 int 1 is greater than int 2 int 1 – le int 2 int 1 is less than or equal int 2 int 1 – lt int 2 int 1 is less than int 2 int 1 – ne int 2 int 1 is not equal to int 2

13 The test command (continue.) OperatorReturns TRUE (zero exit status) if Boolean operators ! exprexpr is FALSE; otherwise returns TRUE expr 1 – a expr 2 expr 1 is TRUE and int 2 is TRUE expr 1 – o expr 2 expr 1 is TRUE or int 2 is TRUE

14 Example: test String Operator test can be quite picky about its arguments The = operator has its highest precedence than the – z operator, so test expects an argument to follow To avoid this sort of problem test X "$symbol'=X $ blanks=" " $ test $blanks $ echo $? 1 $ test "$blanks" $ echo $? 0 $

15 An Abstract format to test test expression  [ expression ] Spaces must appear after [ and before ] $ if [ "$name = Alice ] > then > echo "Hello Alice" > fi $ echo $? 0 $

16 Example: test Integer Operator $ X1="005" $ X2=" 10" $ [ "$X1" = 5 ] $ echo $? 1 $ [ "$X1" -eq 5 ] $ echo $? 0 $

17 Example: test File Operator To test if the file exits [ -f /home/abuzneid/UNIX/aaa ] To test is the file exists and is also readable by the user [ -r /home/abuzneid/UNIX/aaa ]

18 The Logical Negation Operator ! The unary logical operator ! can be placed in front of any other test expression to negate the result of the evaluation of that expression [ ! -r /home/abuzneid/UNIX/aaa ] returns true if /home/abuzneid/UNIX/aaa is not readable [ ! "$X1" = "$X2" ] returns true if $X1 is not identical to $X2 and is equivalent to [ "$X1" != "$X2" ]

19 The Logical AND Operator -a Returns true only, if the two joined expressions are both true [ ! -f "$myfile" – a – r "myfile" ] Returns true if $myfile is an ordinary file and is readable by the user Parentheses can be used in test expression: [ \( "$count" – ge o \) -a \( "$count" – 1t 10 \) ]

20 The Logical OR Operator -o Returns true if either the first expression is true or the second expression is true The – o operator has lower precedence than the – a operator "$a" – eq 0 – o "$b" – eq 2 – a "$c" – eq 10 gets evaluated by test as "$a" – eq 0 – o ("$b" – eq 2 – a "$c" – eq 10) Parentheses can change the order if necessary

21 The else Construct if command t then command 1 command 2 … else command 3 command 4 … fi

22 The exit Command Exit immediately terminates execution of a shell program exit n n: the exit status that you want to be returned If n is not specified, then the exit status used is that of the last command executed before the exit

23 The elseif Construct if command 1 then command … else if command 2 then command … else … if command n then command … else command … fi … fi

24 The elif Construct (continue.) if command1 then command … elif command2 then command … elif commandn then command … else command … Fi

25 The elif Construct (continue.) command 1, command 2 … command n are executed in turn and their exit status tested As soon as one returns an exit status of zero, the commands listed after the then that follows are executed up to another elif, else, or fi If none of the command returns a zero status, then the commands listed after the optional else are executed

26 The case Command case value in pat 1 ) command;; command;; … command;; pat 2 ) command command;; … command;; pat n ) command;; command;; … command;; esac

27 The case Command The word value is compared against the values pat 1, pat 2, … until a match is found When a match is found, the commands listed after the matching value, up to the double semicolons, are executed The shell lets you use *,?,[] special characters with shell The symbol | has the effect of a logical OR when used between two patterns Pat 1 | Pat 2

28 The null Command The format of null command is : Example: suppose you want to check to make sure that the value stored in the variable var exists in the file /home/abuzneid/.profile, and if it doesn't, you want to issue an error message and exit from the program

29 The null Command (continue.) if grep "^var" /home/abuzneid/.profile > then > hello > else > echo "$var does not exit. > exit > fi

30 The && Construct command 1 && command 2 Example: $ sort file1 > /tmp/file2 && mv /tmp/file2 file1 The mv command will be executed only if the sort is successful If $?=0 If $?!=0

31 The || Construct command 1 || command 2 Example: $ grep "$name" phonebook || echo "couldn ’ t find $name" Example: $ who | grep "^name" > /tmp/null || echo "$name is not logged on" If $?!=0 If $?=0

32 The || Construct (continue.) command 3 will be executed if command 1 or command 2 returns zero if command 1 || command 2 then Command 3 fi

33 Shell Script: on Checks if a user is logged in or not To view on click herehere $ on Incorrect number of arguments Usage: on user $ on abuzneid abuzneid is logged on $ on sobh sobh is not logged on

34 Shell Script: greetings Prints greeting wherever you logged in the system To view greetings click herehere $ greetings Good morning

35 Shell Script: rem Removes someone from the phonebook To view rem click herehere $ rem Incorrect number of arguments. Usage: rem name $ rem Abdelshakour $ rem 'Abdelshakour Abuzneid' I coudn't find Abdelshakour Abuzneid in the phone book $ rem Susan More than one match; please qualify further $ rem 'Susan Clinton'

36 Shell Script: number Translates a digit to english To view number click herehere $ number 9 nine $ number 88 Bad argument; please specify a single digit $ number Usage: number digit $

37 Shell Script: charis Classify character given as argument To view charis click herehere $ charis q Please type a single character $ charis 9 Please type a single character $ charis 7 Please type a single character $ sh -x charis 9 + [ 1 -ne 1 ] char=9 + echo 9 + wc -c numchars= 2 + [ 2 -ne 1 ] + echo Please type a single character Please type a single character + exit 1

38 Shell Script: charis2 Classify character given as argument--version 2 To view charis2 click herehere $ charis2 t lowercase letter $ charis2 '>' special character $ charis zzz Please type a single character

39 Shell Script: greetings2 Program to print a greeting case version To view greetings2 click herehere $ date Thu Jan 25 09:14:08 EST 2001 $ greetings2 Good Morning $

40

41 The for Command for var in word 1 word 2 … word n do command … done

42 The for Command (continue.) There is many ways to pass files to for 1. for file in f1 f2 f3 f2 do run $file done 2. for file in f[1-4] do run $file done

43 The for Command (continue.) 3. for file in * do run $file done 4. for file in 'cat filelist' do run $file done

44 The $@ Command Replaces $* when argument are passed to for To view args click herehere $ args a b c number of arguments passed is 3 a b c $ args 'a b' c number of arguments passed is 2 a b c

45 The $@ Command (continue.) shell replaces the value of $* with $1, $2 … shell replaces the value of $@ with "$1", "#2" … The double quotes are necessary around $@, as without them this variable behaves just like $*

46 The $@ Command (continue.) $ args2 a b c number of arguments passed is 3 a b c $ args2 'a b' c number of arguments passed is 2 a b c $ args number of arguments passed is 0 $ args -- version 2 To view args2 click herehere

47 The for without the list Shell will automatically sequence through all of the arguments typed on the command line, just as if you had written in "$@" To view args3 click herehere $ args3 a b c number of arguments passed is 3 a b c $ args3 'a b' c number of arguments passed is 2 a b c $

48 The while Command command 1 is executed and its exit tested If it's zero, then the commands enclosed between do and done are executed Then process continues until command 1 returns nonzero status while command 1 do command … done

49 Shell Program: printargs Print command line arguments are per line To view printargs click herehere $ printargs a b c a b c $ printargs 'a b' c a b c

50 Shell Program: printargs (continue.) $ printargs * Documents args args2 args3 charis greetings mail memos number on personal phonebook printargs Rem $ printargs $ printargs * Documents args args2 args3 charis greetings mail memos number on personal phonebook printargs Rem $ printargs $

51 The until Command The while command continues execution as long as the command listed after the while returns a zero exit status until command1 do command … done

52 Shell Script: monitor Waits until a specified user log on To view monitor click herehere $ monitor Usage: monitor user $ monitor abuzneid abuzneid has logged on

53 Shell Script: monitor2 Wait until a specified user log on -- version2 To view monitor2 click herehere $ monitor2 abuzneid -m Usage: monitor2 [-m] user -m means to be informed by mail $ monitor2 abuzneid abuzneid has logged on $ monitor2 -m abuzneid & 4290

54 Breaking out of a Loop break make an immediate exit from a loop true command returns zero exit status false command returns nonzero exit status break n The n innermost loops are immediately exited

55 Breaking out of a Loop (continue.) Example while true do cmd ='getcmd' if [ "$cmd" = quit ] then break else process cmd "$cmd" fi done

56 Skipping the Remaining Commands in a Loop continue command causes the remaining commands in the loop to be skipped continue n causes the commands in the innermost n loop to be skipped, but execution of the loops then continues normal

57 I/O Redirection on a Loop Input redirection into the loop applies to all commands in the loop that read their data from standard input Output redirection from the loop to a file applies to all commands in the loop that write to standard output Errors can be directed from the standard output to a file by using 2> after the done

58 I/O Redirection on a Loop (continue.) $ for i in 1 2 3 4 > do > echo $1 > done > loopout $ cat loopout $ Example

59 Piping Data into and out of a Loop loop will be run as a subshell Example: $ for i in 1 2 3 4 > do > echo $i > done | wc -l 4 $

60 Typing a loop on one line loop will be run as a subshell Example: $ for i in 1 2 3 4 > do > echo $i > done | wc -l 4 $ if [ 1 = 1 ]; then echo yes; fi yes $ if [ 1 = 2 ]; then echo yes; else echo no; fi no

61 The getopts command Shell provides getopts command to process command line arguments Format: getopts options variable getopts should be executed inside a loop Checks if the argument one after one

62 The getopts command (continue.) getopts returns a zero exit status if The argument begins with minus sign and followed by any signal letter contained inside options. The argument will be saved inside specified variable The letter follows the minus is not listed in the options. It also stores ? inside variable. It also writes an error message to the standard error

63 The getopts command (continue.) getopts returns a nonzero exit status if There are no more arguments left on the command line The next argument doesn't start with minus sign abc option where the command can be executed as command – a – b – c or using stacking feature as command -abc

64 The getopts command (continue.) getopts mt: option where option t has an argument At least one white space character separates the option from the argument, such option cannot be stacked The argument will be stored inside a special variable called OPTARG OPTIND variable is initially set to one, and is updated each line getopts returns to reflect the number of the next command line argument to be processed

65 Shell script: monitor3 monitor3 -m Missing user name! $ monitor3 -x abuzneid monitor3: illegal option -- x Usage: monitor3 [-m] [-t n] user -m means to be informed by mail -t means check every n secs. $ monitor3 -m -t abuzneid & 5614 Wait until a specified user log on – version3 To view monitor3 click herehere

66

67 read Command Format: read variables Shell reads a line from standard input and assigns the first word read to the first variable listed in variables, the second word read to the second variable, and so on Example: read x y Reads a line from standard input, storing the first word read in the variable x, and the reminder of the line in the variable y

68 Serial echo Escape characters CharacterPrints \bBackspace \cThe line without a terminating newline \fFormfeed \nNewline \rCarriage return \tTab character \\Backslash character \nnnThe character whose ASCII value is nnn, where nnn is a one- to three-digit ocatl number with a zero

69 Shell script : mycp copy a file To view mycp click herehere $ ls Unix creation1.sql function1.sql procedure1.sql $ ls UNIX

70 Shell script : mycp (continue.) $ mycp Usage: mycp file1 file2 mycp file(s) dir $ cp mycp /home/abuzneid $ cd.. $ chmod +x mycp $ mycp creation1.sql function1.sql procedure1.sql UNIX $ ls UNIX creation1.sql function1.sql procedure1.sql

71 The $$ variable and Temporary Files $$ contains the process id number of the current process You can use $$ to create a unique file name $ echo Hello … >/tmp/hello$$ $ for i in 1 2 3 4 > do > echo $i > done | wc -l 4

72 The Exit Status from read read can read any number of lines from terminal file read always return zero exit status unless an end of file condition detected on the input: CTRL-d from the terminal no more data to read from the file

73 The script: addi adds pairs of integer on standard input To view addi click herehere $ addi 10 25 35 -5 -10 -15 122 3 125 $ cat data 19 20 -5 -10 20 10 $ addi sums $ cat sums 39 -15 30

74 The script: mynl number lines from files given as argument or from standard input if none supplied To view mynl click herehere $ who | mynl 1: hyunku console Jan 24 00:16 (:0) 2: hyunku pts/4 Jan 24 00:16 (:0.0) 3: sbenayed pts/5 Jan 26 10:05 (1Cust132.tnt64.nyc3.da.uu.net)

75 References UNIX SHELLS BY EXAMPLE BY ELLIE QUIGLEY UNIX FOR PROGRAMMERS AND USERS BY G. GLASS AND K ABLES UNIX SHELL PROGRAMMING BY S. KOCHAN AND P. WOOD


Download ppt "The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between."

Similar presentations


Ads by Google