Top Banner
75

Decisons in Shell Programming

Jan 15, 2016

Download

Documents

NIRAV

Decisons in Shell Programming. 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 - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Decisons  in  Shell   Programming
Page 2: Decisons  in  Shell   Programming

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 commandthen

commandcommand…

fi

Page 3: Decisons  in  Shell   Programming

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

Page 4: Decisons  in  Shell   Programming

The $? Variable

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

Page 5: Decisons  in  Shell   Programming

The $? Variable (continue.)

$ touch file1$ cp file1 file2$ echo $?0$ cp file3 file1cp: cannot access file3$ whohyunku 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 sbenayedsbenayed pts/5 Jan 25 21:01 (216.87.102.199)$ echo $?0

Page 6: Decisons  in  Shell   Programming

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

Page 7: Decisons  in  Shell   Programming

The test command (continue.)

=

Alicetestarguments

$ name=$ test $name = Alicetest: argument expected$ test "$name" = Alice$

test $name = Alice without name null

Page 8: Decisons  in  Shell   Programming

The test command (continue.)

=null

Alicetest

arguments

test $name = Alice with name null

Page 9: Decisons  in  Shell   Programming

File operators in test command

Operator Returns TRUE (zero exit status) if

-b file file is a block special file

-c file file is a character special file

-d file file is a directory

-f file file is an ordinary

-g file file has its set group id (SGID) bit set

-k file file has its sticky bit set

-p file file is a named pipe

Page 10: Decisons  in  Shell   Programming

File operators in test command (continue.)

Operator Returns TRUE (zero exit status) if

-r file file is readable by the process

-s file file has nonzero length

-t file file is open file descriptor associated with a terminal (1 is default)

-u file file has its set user id (SUID) bit set

-w file file is writable by the process

-x file file is executable

Page 11: Decisons  in  Shell   Programming

String operators in test command (continue.)

Operator Returns TRUE (zero exit status) if

string string is not null

-n string string is not null (and string must be seen by test)

-z string string is null (and string must be seen by test)

String1 = string2

string1 is identical to string2

string1 ! = string2

string1 is not identical to string2

Page 12: Decisons  in  Shell   Programming

Integer Comparison Operators in test command (continue.)

Operator Returns TRUE (zero exit status) if

int1 –eq int2 int1 is equal to int2

int1 –ge int2 int1 is greater than or equal to int2

int1 –gt int2 int1 is greater than int2

int1 –le int2 int1 is less than or equal int2

int1 –lt int2 int1 is less than int2

int1 –ne int2 int1 is not equal to int2

Page 13: Decisons  in  Shell   Programming

The test command (continue.)

Operator Returns TRUE (zero exit status) if

Boolean operators

! expr expr is FALSE; otherwise returns TRUE

expr1 –a expr2 expr1 is TRUE and int2 is TRUE

expr1 –o expr2 expr1 is TRUE or int2 is TRUE

Page 14: Decisons  in  Shell   Programming

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 problemtest X "$symbol'=X

$ blanks=" "$ test $blanks$ echo $?1$ test "$blanks"$ echo $?0$

Page 15: Decisons  in  Shell   Programming

An Abstract format to test

test expression [ expression ] Spaces must appear after [ and before ]

$ if [ "$name = Alice ]> then> echo "Hello Alice"> fi $ echo $?0$

Page 16: Decisons  in  Shell   Programming

Example: test Integer Operator

$ X1="005"

$ X2=" 10"

$ [ "$X1" = 5 ]

$ echo $?1

$ [ "$X1" -eq 5 ]

$ echo $?0

$

Page 17: Decisons  in  Shell   Programming

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 ]

Page 18: Decisons  in  Shell   Programming

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" ]

Page 19: Decisons  in  Shell   Programming

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 \) ]

Page 20: Decisons  in  Shell   Programming

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

Page 21: Decisons  in  Shell   Programming

The else Construct

if commandt

thencommand1

command2

…else

command3

command4

…fi

Page 22: Decisons  in  Shell   Programming

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

Page 23: Decisons  in  Shell   Programming

The elseif Construct

if command1then

command command…

elseif command2

thencommandcommand…

else…if commandn

thencommand command…

elsecommandcommand…

fi…

fifi

Page 24: Decisons  in  Shell   Programming

The elif Construct (continue.)

if command1then

command command…

elif command2 then

commandcommand…

…elif commandn

thencommand command…

elsecommandcommand…

Fi

Page 25: Decisons  in  Shell   Programming

The elif Construct (continue.)

command1, command2…commandn 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

Page 26: Decisons  in  Shell   Programming

The case Command

case value inpat1) command;;

command;; … command;;

pat2) command command;;

… command;;

patn) command;; command;;

… command;;

esac

Page 27: Decisons  in  Shell   Programming

The case Command

The word value is compared against the values pat1, pat2, … 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

Pat1 | Pat2

Page 28: Decisons  in  Shell   Programming

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

Page 29: Decisons  in  Shell   Programming

The null Command (continue.)

if grep "^var" /home/abuzneid/.profile

> then

> hello

> else

> echo "$var does not exit.

> exit

> fi

Page 30: Decisons  in  Shell   Programming

The && Construct

command1 && command2

Example:$ sort file1 > /tmp/file2 && mv /tmp/file2 file1The mv command will be executed only if the sort is successful

If $?=0If $?!=0

Page 31: Decisons  in  Shell   Programming

The || Construct

command1 || command2

Example:$ grep "$name" phonebook || echo "couldn’t find $name"

Example:$ who | grep "^name" > /tmp/null || echo "$name

is not logged on"

If $?!=0If $?=0

Page 32: Decisons  in  Shell   Programming

The || Construct (continue.)

command3 will be executed if command1 or command2 returns zero

•if command1 || command2

then

Command3

fi

Page 33: Decisons  in  Shell   Programming

Shell Script: on

Checks if a user is logged in or not To view on click here

$ onIncorrect number of arguments

Usage: on user

$ on abuzneidabuzneid is logged on

$ on sobhsobh is not logged on

Page 34: Decisons  in  Shell   Programming

Shell Script: greetings

Prints greeting wherever you logged in the system

To view greetings click here

$ greetingsGood morning

Page 35: Decisons  in  Shell   Programming

Shell Script: rem

Removes someone from the phonebook To view rem click here

$ remIncorrect number of arguments.Usage: rem name $ rem Abdelshakour$ rem 'Abdelshakour Abuzneid'I coudn't find Abdelshakour Abuzneid in the phone book$ rem SusanMore than one match; please qualify further$ rem 'Susan Clinton'

Page 36: Decisons  in  Shell   Programming

Shell Script: number

Translates a digit to english To view number click here

$ number 9nine$ number 88Bad argument; please specify a single digit$ numberUsage: number digit$

Page 37: Decisons  in  Shell   Programming

Shell Script: charis

Classify character given as argument To view charis click here

$ charis qPlease type a single character$ charis 9Please type a single character$ charis 7Please type a single character$ sh -x charis 9+ [ 1 -ne 1 ]char=9+ echo 9+ wc -cnumchars= 2+ [ 2 -ne 1 ]+ echo Please type a single characterPlease type a single character+ exit 1

Page 38: Decisons  in  Shell   Programming

Shell Script: charis2

Classify character given as argument--version 2 To view charis2 click here

$ charis2 tlowercase letter$ charis2 '>'special character$ charis zzzPlease type a single character

Page 39: Decisons  in  Shell   Programming

Shell Script: greetings2

Program to print a greeting case version To view greetings2 click here

$ dateThu Jan 25 09:14:08 EST 2001$ greetings2Good Morning$

Page 40: Decisons  in  Shell   Programming
Page 41: Decisons  in  Shell   Programming

The for Command

for var in word1 word2…wordn

do

command

command

done

Page 42: Decisons  in  Shell   Programming

The for Command (continue.)

There is many ways to pass files to for1. for file in f1 f2 f3 f2dorun $file

done2. for file in f[1-4]dorun $file

done

Page 43: Decisons  in  Shell   Programming

The for Command (continue.)

3. for file in *

do

run $file

done

4.for file in 'cat filelist'

do

run $file

done

Page 44: Decisons  in  Shell   Programming

The $@ Command

Replaces $* when argument are passed to for To view args click here

$ args a b cnumber of arguments passed is 3abc$ args 'a b' cnumber of arguments passed is 2abc

Page 45: Decisons  in  Shell   Programming

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 $*

Page 46: Decisons  in  Shell   Programming

The $@ Command (continue.)

$ args2 a b cnumber of arguments passed is 3abc$ args2 'a b' cnumber of arguments passed is 2abc$ argsnumber of arguments passed is 0$

args -- version 2 To view args2 click here

Page 47: Decisons  in  Shell   Programming

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 here

$ args3 a b cnumber of arguments passed is 3abc$ args3 'a b' cnumber of arguments passed is 2a bc$

Page 48: Decisons  in  Shell   Programming

The while Command

command1 is executed and its exit tested

If it's zero, then the commands enclosed between do and done are executed

Then process continues until command1 returns

nonzero status

while command1

docommandcommand…

done

Page 49: Decisons  in  Shell   Programming

Shell Program: printargs

Print command line arguments are per line To view printargs click here

$ printargs a b cabc$ printargs 'a b' ca bc

Page 50: Decisons  in  Shell   Programming

Shell Program: printargs (continue.)

$ printargs *Documentsargsargs2args3charisgreetingsmailmemosnumberonpersonalphonebookprintargsRem$ printargs

$ printargs *Documentsargsargs2args3charisgreetingsmailmemosnumberonpersonalphonebookprintargsRem$ printargs $

Page 51: Decisons  in  Shell   Programming

The until Command

The while command continues execution as long as the command listed after the while returns a zero exit status

until command1do

commandcommand…

done

Page 52: Decisons  in  Shell   Programming

Shell Script: monitor

Waits until a specified user log on To view monitor click here

$ monitorUsage: monitor user$ monitor abuzneidabuzneid has logged on

Page 53: Decisons  in  Shell   Programming

Shell Script: monitor2

Wait until a specified user log on -- version2 To view monitor2 click here

$ monitor2 abuzneid -mUsage: monitor2 [-m] user -m means to be informed by mail$ monitor2 abuzneidabuzneid has logged on$ monitor2 -m abuzneid &4290

Page 54: Decisons  in  Shell   Programming

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

Page 55: Decisons  in  Shell   Programming

Breaking out of a Loop (continue.)

Examplewhile truedo

cmd ='getcmd'if [ "$cmd" = quit ]then

breakelse

process cmd "$cmd"fi

done

Page 56: Decisons  in  Shell   Programming

Skipping the Remaining Commands in a Loop

continue command causes the remaining commands in the loop to be skipped continue ncauses the commands in the innermost n

loop to be skipped, but execution of the loops then continues normal

Page 57: Decisons  in  Shell   Programming

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

Page 58: Decisons  in  Shell   Programming

I/O Redirection on a Loop (continue.)

$ for i in 1 2 3 4

> do

> echo $1

> done > loopout

$ cat loopout

$

• Example

Page 59: Decisons  in  Shell   Programming

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$

Page 60: Decisons  in  Shell   Programming

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; fiyes$ if [ 1 = 2 ]; then echo yes; else echo no; fino

Page 61: Decisons  in  Shell   Programming

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

Page 62: Decisons  in  Shell   Programming

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

Page 63: Decisons  in  Shell   Programming

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 ascommand –a –b –c

or using stacking feature ascommand -abc

Page 64: Decisons  in  Shell   Programming

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

Page 65: Decisons  in  Shell   Programming

Shell script: monitor3

monitor3 -mMissing user name!$ monitor3 -x abuzneidmonitor3: illegal option -- xUsage: 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 here

Page 66: Decisons  in  Shell   Programming
Page 67: Decisons  in  Shell   Programming

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

Page 68: Decisons  in  Shell   Programming

Serial echo Escape characters

Character Prints

\b Backspace

\c The line without a terminating newline

\f Formfeed

\n Newline

\r Carriage return

\t Tab character

\\ Backslash character

\nnn The character whose ASCII value is nnn, where nnn is a one- to three-digit ocatl number with a zero

Page 69: Decisons  in  Shell   Programming

Shell script : mycp

copy a file To view mycp click here

$ lsUnix creation1.sql function1.sql procedure1.sql $ ls UNIX

Page 70: Decisons  in  Shell   Programming

Shell script : mycp (continue.)

$ mycpUsage: mycp file1 file2 mycp file(s) dir $ cp mycp /home/abuzneid$ cd ..$ chmod +x mycp$ mycp creation1.sql function1.sql procedure1.sql UNIX$ ls UNIXcreation1.sql function1.sql procedure1.sql

Page 71: Decisons  in  Shell   Programming

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

Page 72: Decisons  in  Shell   Programming

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

Page 73: Decisons  in  Shell   Programming

The script: addi

adds pairs of integer on standard input To view addi click here

$ addi10 2535-5 -10-15122 3125$ cat data19 20-5 -1020 10$ addi <data>sums$ cat sums39-1530

Page 74: Decisons  in  Shell   Programming

The script: mynl

number lines from files given as argument or from standard input if none supplied

To view mynl click here

$ who | mynl1: 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)

Page 75: Decisons  in  Shell   Programming

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