Professional Documents
Culture Documents
Objectives
In this lecture you will learn
Shell variables Writing shell program Pass an arguments Add, remove and lookup into a file The shift command
Example[1]
$ cat run tbl $1 |nroff mm Tlp |lp $ chmod +x run
Example[2]
$ who
root tty02 Jul 7 08:37 fred tty03 Jul 8 08:30 tony tty04 Jul 8 08:17 lulu tty05 Jul 8 08:27 taziz tty06 Jul 8 08:57 ahmed tty07 Jul 8 08:47
$ cat ison who | grep $1 Execute it with taziz as the argument $ ison taziz
taziz tty19 Jul 8 08:30
$ ison taziz $
The $# Variable
The shell variable $# gives you the number of arguments that were typed on the command line.
$ cat args echo $# arguments passed echo arg 1 =:$1: arg 2=:$2: arg 3=:$3: $ args a b c 3 arguments passed arg 1 =:a: arg 2=:b: arg 3=:c:
$# Example[1]
$ args a b 2 arguments passed arg 1 =:a: arg 2=:b: arg 3=:: $ args 0 arguments passed arg 1 =:: arg 2=:: arg 3=:: $ args "a b c" 1 arguments passed arg 1 =:a b c: arg 2=:: arg 3=::
$# Example[2]
See what files start with x
$ ls x* xact xtra $ args x* 2 arguments passed arg 1 =:xact: arg 2=:xtra: arg 3=:: $ my_bin=/usr/steve/bin $ args $my_bin 1 arguments passed arg 1 =:/usr/steve/bin: arg 2=:: arg 3=::
$# Example[3]
Pass the contents if names
$ args `cat names` 7 arguments passed arg 1 =:fil1: arg 2=:fil2: arg 3=:fil3: $
The $* Variable
The special variable $* references all arguments passed to the program.
$ cat args2 echo $# arguments passed echo they are :$*: $ args a b c 3 arguments passed they are :a b c:
7 arguments passed they are :args args2 names nu phonebook stat xact xtra:
Add in Phonebook
$ cat add # # add someone to the phone book # echo "$1 $2" >> phonebook $ $ add 'Tariq Aziz' 230-4958 $ lu Tariq Tariq Aziz 230-4958 $
Phonebook
$ cat phonebook Alice Chebba 596-2015 Bob Swingle 598-9257 Liz Stachiw 775-2298 Susan Goldberg 338-7776 Susan Topple 243-4932 Tony Iannino 386-1295
Tariq Aziz 230-4958
Phonebook
$ cat phonebook Alice Chebba 596-2015 Bob Swingle 598-9257 Liz Stachiw 775-2298 Susan Goldberg 338-7776 Susan Topple 243-4932 Tony Iannino 386-1295 Tariq Aziz 230-4958 Billy Bach 331-7618 $