You are on page 1of 91

Lecture 2: More UNIX,

Bash Shell Scripting


Programming Tools And
n!ironments
"#$ecti!e
"#$ecti!e: To introduce students to the concept
o% a shell, e%%ecti!e use o% the shell, the shell as
programming language, and shell scripts& 'e (ill
use the #ash shell %or the e)amples and details
pro!ided&

Shell s*nta) and commands

histor* and command completion

$o# control

!aria#les

programming constructs

scripts
'hat does the shell do+
In Uni), separate %rom the "S ,change loo-
and %eel./
reads and e)ecutes commands

some handled #* the shell itsel% ,p(d, echo,0./

some are programs stored in some director* ,loo- in


directories in PAT1.& Start a su#shell to e)ecute
these
Pro!ides support %or #etter interaction (ith the
computer2"S ,command histor*, editing,
con%iguration./
Supports scripting ,is a programming
language./
)ecuting a 3ommand
A%ter reading a command, the shell ma* do some
processing ,see (ildcards, etc in the s*nta) description
that %ollo(s., then it must %ind a program to e)ecute
the command&
Some commands are e)ecuted directl* #* the shell&
"ther commands are e)ecuted #* separate programs&
These are %ound #* loo-ing in a list o% directories %or
programs (ith the appropriate name& The shell
searches directories in the PAT1 !aria#le& A hash ta#le
is used to ma-e the search %ast& 4ou can add ne(
commands simpl* #* adding ne( programs ,a program
can #e an* e)ecuta#le %ile including scripts 5 re!ie(
Uni) permissions. to directories in the PAT1& 4ou can
modi%*2add directories in the PAT1&
6inding out a#out 3ommands
type 5 tells *ou i% a command is a #uilt7in, an
alias, or a program ,e)ternal to the shell./
which 5 tells in (hich director* a utilit* is
located
help 5 displa*s in%ormation a#out #uilt7in
commands ,it is a #uiltin itsel%./
info bash 5 a good place to read a#out the
BAS1 shell
)ample
[jjohnson@ws44 cs265]$ which echo
2#in2echo
[jjohnson@ws44 cs265]$ type -a echo
echo is a shell #uiltin
echo is 2#in2echo
[jjohnson@ws44 cs265]$ help echo 8 help pro!ides in%ormation on #uiltin commands
echo: echo 97ne: 9arg &&&:
"utput the A;<s& I% 7n is speci%ied, the trailing ne(line is
suppressed& I% the 7e option is gi!en, interpretation o% the
%ollo(ing #ac-slash7escaped characters is turned on:
=a alert ,#ell./
=# #ac-space
=c suppress trailing ne(line
= escape character
=% %orm %eed
=n ne( line
=r carriage return
=t hori>ontal ta#
=! !ertical ta#
== #ac-slash
=num the character (hose AS3II code is NUM ,octal.&

4ou can e)plicitl* turn o%% the interpretation o% the a#o!e characters
(ith the 7 option&
Initialisation 6iles

commands & variables read when shell is


started

if variables are placed in system-wide init files,


available to every shell

customizations must be exported to be available

commands & aliases cannot be exported so


must be placed in user-specific init
2etc2pro%ile 7
S*stem7'ide Initiali>ation 6ile
;ead %irst #* shell
Tas-s accomplished:

Sets and e)ports !aria#les:

PAT1, T;M, PS?, etc&

@ispla*s contents o% 2etc2motd ,msg o% the


da*./

Sets de%ault %ile creation permissions


,umas-./
User7speci%ic initialisation
I% the shell is a login shell, it loo-s %or
one o% the %ollo(ing ,in order./

A2&#ashBpro%ile

A2&#ashBlogin

A2&pro%ile
I% a non7login interacti!e shell, reads

A2&#ashrc
"ther customi>ations
PS? 5 prompt
PAT1 5 add to the search path
Set shell options

noclo##er

ignoreeo%

command7line editing option ,!i or emacs./


See ~kschmidt/Public/.bash_profile
and .bashrc %or e)amples

,6eel %ree to ta-e them, as *ou (ish./


Shell Caria#les
The shell -eeps trac- o% a set o%
parameter names and !alues&
Some o% these parameters determine
the #eha!ior o% the shell&
'e can access these !aria#les:

set ne( !alues %or some to customi>e the


shell&

%ind out the !alue o% some to help


accomplish a tas-&
)ample Shell Caria#les
sh / ksh / bash
PWD current (or-ing director*
PATH list o% places to loo- %or
commands
HOME home director* o% user
MAIL (here *our email is stored
TERM (hat -ind o% terminal *ou ha!e
HISTILE (here *our command
histor* is sa!ed
@ispla*ing Shell Caria#les
Pre%i) the name o% a shell !aria#le (ith
DED to dere%erence
The echo command (ill do:
echo !HOME
echo !PATH
4ou can use these !aria#les on an*
command line:
ls "al !HOME
Setting Shell Caria#les
4ou can change the !alue o% a shell
!aria#le (ith an assignment command
,this is a shell #uiltin command.:
HOME#/etc
PATH#/$s%/bin&/$s%/etc&/sbin
'EW(AR#)blah blah blah)
Note the lac- o% spaces around the FGF
export
e)port a !aria#le
ma-e it a!aila#le to su#shells

!alue passed in

changes made to a !alue in the su#shell do


not persist in the caller
Su#shell is created (hene!er a script or
a program is run

Inherits parent shellFs e)ported !aria#les


The PATH
ach time *ou gi!e the shell a command line it
does the %ollo(ing:

3hec-s to see i% the command is a shell #uilt7in&

I% not 7 tries to %ind a program (hose name ,the


%ilename. is the same as the command&
The PATH !aria#le tells the shell (here to loo-
%or programs ,non #uilt7in commands.&
echo !PATH
####### *+$een, " --&./&01 #######
2 echo !PATH
/
ho3e/openwin/bin&/$s%/bin&/bin&/$s%/local/b
in&/$s%/sbin&/$s%/bin/400&/$s%/5a3es&/$s%/l
ocal/packa5es/netscape
The PATH is a list o% D:D delimited directories&
The PATH is a list and a search order&
4ou can add stu%% to *our PAT1 #* changing the
shell startup %ile&
Notes a#out PAT1
I% *ou do not ha!e & in *our PAT1, commands
in *our current director* (ill not #e %ound& 4ou
ma* or ma* not (ant to add & to *our PAT1& I%
*ou do not and (ant to e)ecute a command in
the current director*

&2command
The PAT1 is searched seHuentiall*, the %irst
matching program is e)ecuted& Be(are o%
naming *our e)ecuta#les test as there is
another program called test and this ma* #e
e)ecuted (hen *ou enter

test
PAT1
9$$ohnsonI(sJJ so%t(are:E echo EPAT1
2usr2local26rameMa-er2#in:2home2$$ohnson2#in:2usr2local2gpl2mpich7
?&2&J2#in:2usr2local2#in:2usr2s#in:2s#in:2usr2open(in2#in:2opt2SUN'spr
o2#in:2usr2ccs2#in:2usr2uc#:2usr2s#in:2usr2#in:2etc:2usr2etc:2usr2UTILS2
pu#lisher2#in:2usr2#in2X??:2#in:2usr2remote2algBso%t2linda2&K&2sol2&L2#i
n:&
9$$ohnsonI(sJJ so%t(are:E PAT1GEMPAT1N:2home2$$ohnson2so%t(are
9$$ohnsonI(sJJ so%t(are:E echo EPAT1
2usr2local26rameMa-er2#in:2home2$$ohnson2#in:2usr2local2gpl2mpich7
?&2&J2#in:2usr2local2#in:2usr2s#in:2s#in:2usr2open(in2#in:2opt2SUN'spr
o2#in:2usr2ccs2#in:2usr2uc#:2usr2s#in:2usr2#in:2etc:2usr2etc:2usr2UTILS2
pu#lisher2#in:2usr2#in2X??:2#in:2usr2remote2algBso%t2linda2&K&2sol2&L2#i
n:&:2home2$$ohnson2so%t(are
set command ,shell #uiltin./
The set command (ith no parameters
(ill print out a list o% all the shell !ari#les&
Some common options:

noclobber 5 Oeeps mv, cp, redirection


%rom deleting an e)isting %ile

-o vi ,or -o emacs. 5 sets command7line


editing mode

ignoreeof 5 ctrl7@ (onFt e)it the shell


!PS0 and !PS-
The PS0 shell !aria#le is *our command
line prompt&
The PS- shell !aria#le is used as a
prompt (hen the shell needs more input
,in the middle o% processing a
command.&
B* changing PS? and2or PS2 *ou can
change the prompt&
6anc* bash prompts
Bash supports some %anc* stu%% in the
prompt string:
6t is replace #* the current time
6w is replaced #* the current director*
6h is replaced #* the hostname
6$ is replaced #* the username
6n is replaced #* a ne(line
)ample bash prompt
####### *+$een, " --&./&01 #######
2 echo !PS0
####### *6h, " 6t #######6n6w
4ou can change *our prompt #*
changing PS?:
PS0#)7es Maste%8 )
Ma-ing 3hanges Stic-
I% *ou (ant to tell the shell ,bash. to
al(a*s use the prompt D7es Maste% 8D,
*ou need to store the change in a shell
startup %ile&
6or bash 7 change the %ile A2&#ashrc&
S1LL
The S1LL !aria#le holds the path o% the
login shell&
1"M
The 1"M !aria#le contains the PAT1 to *our
home director*&
'hen *ou use cd command (ith no arguments,
the command uses the !alue o% the 1"M
!aria#le as the argument&
echo E1"M
2home2!>a*chi-
Metacharacters
Shell metacharacters are characters that are
handled speciall* #* the shell&
Belo( is an ,incomplete. list o% shell
metacharacters

P PP Q QQ R 3ommand redirection, pipe

S 9: + MN 6ile speci%ication

T U RR UU ,. 3ommand SeHuencing
Metacharacters ,cont./
D, F <rouping Te)t

@ou#le Huotes and single Huotes indicated that the


enclosed te)t is to #e treated as a unit, not as a
group o% (ords&
8 3ommenting

;est o% line a%ter these characters is ignored


= ,#ac-slash. 5 the escape character

Indicates that the character immediatel* %ollo(ing


the #ac-slash is to #e treated literall*&

To remo!e a %ile named V8#ogusW *ou can use the


#ac-slash
rm =8#ogus
Aliases
3ommands can #e aliased ,renamed. to alter
their #eha!ior& A common used o% aliases is to
add options to the de%ault #eha!ior o% certain
commands ,e&g& ls, rm, m!, 0./
It is common practice to alias rm to prompt the
user to ma-e sure that the speci%ied %iles
should #e remo!ed& This is especiall*
important since *ou can remo!e all %iles (ith
,see (ildcards./

rm S
To see current aliases, use the alias command,
this can also #e used to set ne( aliases&
Alias ,cont./
3reate an alias using the #uiltin command
alias name9G!alue:

4ou should usuall* enclose !alue in Huotes&

no spaces around the FGF

'ithout a !alue, alias prints out the alias associated


(ith name
alias dirGVlsW
alias lsGVls 736W
dir
"utput same as %or Vls 736W
Caria#le Su#stitution
Shells support the use o% !aria#les
A !aria#le is a name that is #ound to a !alue&
To set a !aria#le ,in Bash. $ust enter
nameG!alue

No spaces around FGF


To see the settings o% all !aria#les $ust enter
VsetW&
To -ill a !aria#le:
unset name
Caria#le Su#stitution ,cont./
'hen processing a command, !aria#le
su#stitution occurs&
A !aria#le in a command is %lagged #* a
dollar sign pre%i) VEW
$ echo My shell is !SHELL
M* shell is 2#in2#ash

echo 'rites out its arguments a%ter su#stitution


is per%ormed&
Caria#le Su#stitution ,cont./
Caria#le su#stitution (ill occur (ithin
dou#le Huotes
$ echo )My shell is !SHELL)
My shell is /usr/local/bin/tcsh
Su#stitution does not occur (ithin single
Huotes&
$ echo 9My shell is !SHELL9
My shell is $!"##
Caria#le Su#stitution ,cont./
'hen the usage o% a !aria#le name is not
clear, enclose it (ithin #races EMnameN
$ p%efi:#cs-;<
$ s$ffi:#=p>f
$ echo !p%efi:?/!s$ffi:
.pdf
$ echo !@p%efi:A?/!@s$ffi:A
cs$%&'(.pdf
This occurs (hen constructing %ile names in
script %iles&
Caria#le Su#stitution ,cont./
Man* programs use shell !aria#les ,also called
en!ironmental !aria#les. to get con%iguration
in%ormation&
)amples

P;INT; is used #* printing commands to


determine the de%ault printer&

T;M is used #* programs ,e&g&, !i, pine. to


determine (hat t*pe o% terminal is #eing used&

CISUAL is used #* net(or- ne(s programs, etc&, to


determine (hat editor to use&
3ommand Su#stitution
3ommand su#stitution allo(s the output ,stdout. o%
a command to replace the command name& There
are t(o %orms:
The original Bourne:
)command)
The Bash ,and Oorn. e)tension:
$*command+,
3ommand7su#stitution
The output o% the command is su#stituted in:
$ echo !BlsC
foo fee file-
$ echo )To>ay is !B>ate 9DEA E> EF E79C)
.oday is .hursday (' eptember $'/'
Strong Huoting 5 Single Huotes
Inhi#its all su#stitution, and the special
meaning o% metacharacters:
$ echo 9!GSER is !GSER9
$0"1 is $0"1
$ echo 9to>ay is H>ateH9
today is )date)
$ echo 9'o back5%o$n>I9
2o background3
$ echo 9I sai>J )%a>ioK)9
4 said5 6radio6
'ea- Huoting 5 dou#le Huotes
Allo(s command and !aria#le
su#stitution
Inhi#its special meaning o% all other
metacharacters
$ echo )My na3e is !GSER I)
My name is kschmidt 3
$ echo )6!-=?? says H>ateH)
$$.'' says un 7an /& '/89(8($
". $''
3ommand )ecution
Sometimes (e need to com#ine se!eral commands&
There are %our %ormats %or com#ining commands
into one line: seHuenced, grouped, chained, and
conditional&
A seHuence o% commands can #e entered on one
line& ach command must #e separated %rom its
predecessor #* semicolon&
There is no direct relationship #et(een the
commands&
co33an>0L co33an>-L co33an>/
<rouped 3ommands
I% (e appl* the same operation to the group, (e
can group commands
3ommands are grouped #* placing them into
parentheses
3ommands are run in a su#shell
)ample:
echo MMonthN O fileL cal 0? -??? OO file
Becho MMonthN L cal 0? -??? C O file
3onditional 3ommands
'e can com#ine t(o or more commands using
conditional relationships AN@ ,UU. and "; ,RR.&
I% (e AN@ t(o commands, the second is e)ecuted
onl* i% the %irst is success%ul&
I% (e "; t(o commands, the second is e)ecuted
onl* o% the %irst %ails&
cp file0 file- II echo MPopy s$ccessf$lN
cp file0 file- QQ echo MPopy faile>N

Shell S*nta)
3omments

8 This is a comment

ls 8 list the %iles in the current director*


Line continuation

echo A long =

P line
T 83ommand separator 5 *ou can list more
than one command per line separated #* T

ls T (ho
2 8Pathname separator

cd 2home2$$ohnson
Shell S*nta) 5
(ildcards ,glo##ing./
'ildcards, and pathname e)pansion

S 8 match an* string ,including empt*./

+ 8 match an* single character

9set: 8 match characters listed in set ,can #e


range./

9Xset: 8 match an* character not gi!en in set


)amples

ls S&c

ls S&+

ls S&91h:9Tt:9Ll:

ls 9a7>:
Shell S*nta) 5
redirection and pipes
6ile redirection and pipes

Q 8 redirect input %rom speci%ied source

P 8 redirect output to speci%ied source

PP 8 redirect output and append to speci%ied


source

R 8 pipe the output %rom one command to the


input to the ne)t
)amples

grep (ord Q 2usr2dict2(ords

ls P listing

ls PP listing

ls 7lR (c 7l
Shell S*nta) 7 stderr
Note %ile redirection o% standard output
9stdout: does not include error messages,
(hich go to standard error 9stderr: ,(hen
*ou are in a terminal session, #oth stdout and
stderr go to the screenT ho(e!er, (hen *ou
redirect stdout to a %ile, stderr still goes to the
screen.&
stdout is designated #* the %ile descriptor ?
and stderr #* 2 ,standard input is Y./

To redirect standard error use 2P

ls %ilenothere P listing 2P error

ls %ilenothere 2PU? P listing 8 #oth stdout and


stderr redirected to listing
Shell S*nta) 5 #g $o#s
Bac-ground $o#s

3 8 run command in the #ac-ground


grep :;e.<:= /usr/;ord/dict > ;e;ords 3

This runs the grep command in the #ac-ground 5


*ou immediatel* get a ne( prompt and can
continue *our (or- (hile the command is run&

?obs @ Builtin& Lists acti!e $o#s ,stopped, or


running in the #ac-ground.& Also see the command
ps

kill (ill ta-e a PI@ ,see ps. or $o#spec ,see ?obs.


'hat Is A Script+
A script is a small program that is e)ecuted #*
the shell&
The script is a te)t %ile (hich (ill contain:

Shell commands *ou normall* use&

Shell %lo( control constructs ,e&g&, i%7then7else, etc&./

A hea!ier use o% !aria#les than *ou normall* (ould


use %rom the command line&
'h* 'rite Scripts+
An* tas- *ou do ,#* hand. more than t(ice
should pro#a#l* #e (rapped into a script
SeHuences o% operations (hich *ou per%orm
o%ten can #e placed into a script %ile and then
e)ecuted li-e a single command&

6or e)ample, renaming all %iles o% the %orm


cs2ZKlS&ppt to cs2ZKlSn&ppt reHuires a m! command
%or each %ile&
The Uni) shells are !er* po(er%ul, #ut there
are some things that the* do not do (ell&
Shell scripting 7 'h* Not +
resource7intensi!e tas-s, especiall* (here speed
is a %actor
comple) applications, (here structured
programming is a necessit*
mission7critical applications upon (hich *ou are
#etting the ranch, or the %uture o% the
compan*
situations (here securit* is important, (here *ou
need to protect against hac-ing
'h* Not + ,cont&./
Pro$ect consists o% su#components (ith
interloc-ing dependencies
)tensi!e %ile operations reHuired ,Bash is
limited to serial %ile access, and that onl*
in a particularl* clums* and ine%%icient
line7#*7line %ashion./
Need to generate or manipulate graphics
or <UIs
'h* Not + ,cont&./
Need direct access to s*stem hard(are
Need port or soc-et I2"
Need to use li#raries or inter%ace (ith
legac* code
Cer* Simple Script
#!/bin/sh
echo Hello World
)ample: Simple Script
Let[s create a shell script to gi!e us
in%ormation a#out the s*stem&
'e create the script using a te)t editor&

Let[s call the %ile VstatusW


AB/bin/bash
uptime
users
Be sure to insert an VenterW a%ter the last line&

)it the editor


;unning a Script
To e)ecute the shell (e can do
$ bash stat$s
/'8(C up $( days5 $(8&95 /9 users5
load average D
af?h? billc D
'e can also e)ecute the %ile as a command i%
the appropriate e)ecute access is granted&
$ ./stat$s
bash8 ./status8 Permission denied
$ ch3o> D: stat$s
$ ./stat$s A Works correctly.
8X 5 Dsha7#angD
Not needed i% #ash -ic-s o%% the script,
#ut0
Shells loo- %or D8XD at the !er* #eginning
o% the %ile
It is %ollo(ed #* the program
,interpreter. that (ill read this %ile:

AB/bin/bash

AB/usr/bin/Python
A this is a Python program. Eash
A doesn:t read it. Fives it right
A to the Python interpreter
3onditional )pressions
To per%orm i%s and (hiles (e need to #e a#le
to construct conditional e)pressions&
A conditional e)pression is one that
e!aluates to true or %alse depending on
its operands
A process[ return !alue o% Y is ta-en to
#e true T an* non>ero !alue is %alse
test - 3onditional )pressions
Actuall* a dis- utilit*
9 is $ust shorthand
Pro!ides %or a great man* tests
Is a!aila#le to all shells
test e)pression
"r
9 e)pression : Separate e)pression %rom #rac-ets
spaces
3onditional )pressions ,cont./
test returns an e)it status o% >ero ,success. i%
the e)pression e!aluates to true&
test uses a !ariet* o% operators

Unar* %ile operators can test !arious %ile properties&


1ere are $ust a %e(:

7eTrue i% %ile e)ists

7% True i% %ile is a regular %ile

7d True i% %ile is a director*

7( True i% %ile e)ists and is (rita#le

7" True i% I o(n the %ile

&g&
if G -e ~kschmidt/public_html H I then
echo 6Jurt has a public ;eb directory6
fi
9: 5 %ile and string operators

Binar* %ile operators V%ile? op %ile2W

7nt True is %ile? is ne(er than %ile2

7ot True is %ile? is older than %ile2

7e% True i% %? and %2 re%er to the same inode

Unar* string operators Vop stringW

7> True i% string is o% >ero length

7n True i% string is not o% >ero length

7l ;eturns length o% string

&g&
if G -K 6$myLar6 H I then
echo 6M$myLar has null length6
fi
9: 5 string operators

These compare le)ical order

NN BN = > =N >N

Note, Q P are %ile redirection& scape them

&g&
if G 6abc6 BN 6OEP6 H I then
echo :ee. Pase matters.: I fi
if G /$ M= $ H I then
echo 6/$ is less than $-6 I fi
9: 5 arithmetic operators
"nl* %or integers
Binar* operators:
-lt -gt -le -ge -eQ -ne
&g&
if G $ @le ( H I then Iecho 6coolB6 I fi
xN&
if G 6$x6 @ne /$ H I then
echo 6till cool6 I fi
9: 5 Logical "perators

Logical e)pression tools

X e)pression Logical not ,I&e&, changes sense o%


e)pression./

e? 7a e2 True i% #oth e)pressions are true&

e? 7o e2 True i% e? or e2 is true&

=, e)pression =. 'or-s li-e normal parentheses %or


e)pressionsT use spaces
around the e)pression&
Examples:
test -e bin -a -d /bin is true
G -e ~/.bashrc -a B -d ~/.bashrc H 33 echo
true
99 test ::
Bash added 99:: %or more 37li-e usage:
if GG -e ~/.bashrc 33 B @d ~/.bashrc HH
then
echo 6#et:s parse that puppy6
fi
if GG -K 6$myRile6 SS B @r $myRile HH
D
ItFs a #uilt7in
'h* sometimes Huote Em*6ile, sometimes not ,itFs
usuall* a good idea to do so.+
Arithmetic )pressions
Bash usuall* treats !aria#les as strings&
4ou can change that #* using the arithmetic
e)pansion s*nta): ,, arithmetic)pr ../
,,.. shorthand %or the let #uiltin statement
$ :#0
$ :#:D0 A 6xT/6 is ?ust a string
echo !:
xT/
Note, E9: is deprecated
Arithmetic )pression ,cont./
$ :#0
$ :#!:D0 A still ?ust a string
$ echo !:
/T/

3loser, #ut still not right&


$ :#0
$ BB :#:D0 CC
! echo !:
$

6inall*X
Sample: Basic conditional
e)ample i% && then
AB/bin/bash
if G 6$/6 N 6foo6 H I then
echo expression M
evaluated as true
fi
Sample: Basic conditional
e)ample i% && then &&& else
AB/bin/bash
if G 6$/6 N 6foo6 H
then
echo :Rirst argument is 6foo6:
else
echo :Rirst arg is not 6foo6:
fi
Sample: 3onditionals (ith
!aria#les
AB/bin/bash
./N6foo6
.$N6bar6
if G 6$./6 NN 6$.$6 H I then
echo expression evaluated as true
else
echo expression evaluated as false
fi

Al(a*s Huote !aria#les in scriptsX


3hec-ing return !alue o% a
command
if diff 6$fileO6 6$fileE6 > /dev/null
then
echo 6Riles are identical6
else
echo 6Riles are different6
fi
3ase Statement
case $opt in
a + echo 6option a6II
b + echo 6option b6II
c + echo 6option c6II
M- + echo M
:usage8 alice G-aH G-bH G-cH args...:
exit /II
esac
Special Caria#les
E8 the num#er o% arguments
ES all arguments
EI all arguments ,Huoted indi!iduall*./
E+ return !alue o% last command
e)ecuted
EE process id o% shell
E1"M, EI6S, EPAT1, EPS?, EPS2
Scripts and Arguments
Scripts can #e started (ith parameters, $ust
li-e commands
aScript arg? arg2 0
The scripts can access these arguments
through shell !aria#les:

VEnW Is the !alue o% the n


th
paramter&

The command is parameter >ero

VE8W Is the num#er o% parameters entered&

VESW )pands as a list o% all the parameters entered


e)cept the command&
Scripts and Parameters ,cont./
Let[s Huic-l* (rite a script to see this:

,this %irst line is a Huic- and dirt* (a* to (rite a %ile./


$ cat O :: R cat reads from stdin if no
file specified
echo $'
echo $A
echo $/ $$
echo $<
P-d A Control-D is the end of file
character.
$ ch3o> D: ::

The %ile )) is no( an e)ecuta#le shell script&


Scripts and Parameters ,cont./
$ ./:: a b c
./xx
(
a b
a b c
$ ::
./xx
'
Unspeci%ied parameters e)pand as
empt* strings ,I&e&&, as nothing./
Loops %or, (hile and until
The %or loop is a little #it di%%erent %rom other
programming languages& Basicall*, it letFs *ou
iterate o!er a series o% F(ordsF (ithin a string&
The (hile e)ecutes a piece o% code i% the
control e)pression is true, and onl* stops
(hen it is %alse ,or a e)plicit #rea- is %ound
(ithin the e)ecuted code&
The until loop is almost eHui!alent to the
(hile loop, e)cept that the code is e)ecuted
(hile the control e)pression e!aluates to
%alse&
6or samples
)ample
$ fo% : in 0 - aL >o
> echo !:
> >one
/
$
a
)ample
$ fo% : in SL >o
> echo !:
> >one
bin
mail
public_html
D
6or samples
RK/bin/bash
fo% i in !Bcat list=t:tC L >o
echo ite3& !i
>one
RK/bin/bash
fo% BB i#?L iT0?L DDi CC L >o
echo ite3& !i
>one
'hile sample
POG'TER#?
while BB POG'TER T 0? CC L >o
echo The co$nte% is !POG'TER
BB POG'TER # POG'TERD0 CCU
>one
POG'TER#?
while * !POG'TER "lt 0? , L >o
echo The co$nte% is !POG'TER
let POG'TER#POG'TERD0
>one
Until sample
RK/bin/bash
POG'TER#-?
$ntil * !POG'TER "lt 0? ,
>o
echo POG'TER !POG'TER
let POG'TER"#0
>one
)ample: ;enaming
<oal: ;ename all the %iles o% the %orm
cs2ZKlS&ppt to cs2ZKlS&e)e (here S
should #e Y2, YL 0 ?Y&
Solution: %or loop

%or n in Y2 YL YJ YK YZ Y\ Y] Y^ ?YT do
m! cs2ZKlEn&ppt cs2ZKlEn&e)e
done

Mo!es cs2ZKlY2&ppt to cs2ZKlY2&e)e,


cs2ZKlYL&ppt to cs2ZKlYL&e)e, etc&
)ample: ;enaming ,cont.
Better:
for ** nN$I n=/'I TTi ++ I do
mv cs$%&l'$n.ppt cs$%&l'$n.exe
done
mv cs$%&l/'.ppt cs$%&l/'.exe
Better still:

'rite a script, pad, that (ill pad on the le%t

3ount directl* %rom 2 to ?Y


Loop 3ontrol
break terminates the loop
continue causes a $ump to the ne)t
iteration o% the loop
@e#ugging Tip
I% *ou (ant to (atch the commands actuall*
#eing e)ecuted in a script %ile, insert the line
Vset 7)W in the script&
set 7)
%or n in ST do
echo En
done

'ill displa* the e)panded command #e%ore e)ecuting it&


_ echo #in
#in
_ echo mail
mail
6unctions
As in almost an* programming language, *ou can use
%unctions to group pieces o% code in a more logical (a*
or practice the di!ine art o% recursion&
@eclaring a %unction is $ust a matter o% (riting %unction
m*B%unc M m*Bcode N&
3alling a %unction is $ust li-e calling another program, *ou
$ust (rite its name&
Local !aria#les
AB/bin/bash
!"##UN!ello
function hello V
local !"##UNWorld
echo $!"##U
X
$ echo $!"##U
$ hello
$ echo $!"##U
6unctions (ith parameters
sample
RK/bin/bash
f$nction +$it @
echo 9Voo>byeK9
e:it
A
f$nction hello @
echo )Hello !0)
A

fo% na3e in (e%a W$%t L
>o
hello !na3e
>one
+$it
Output:
!ello Lera
!ello Jurt
FoodbyeB
Parameter )pansion
EMparameter:7(ordN

Use @e%ault Calues&


EMparameter:G(ordN

Assign @e%ault Calues&


EMparameter:+(ordN

@ispla* rror i% Null or Unset&


EMparameter:_(ordN

Use Alternate Calue&


More Parameter )pansion
'e can remo!e parts o% a !alue:

EMparam8patternN

EMparam88patternN
7 remo!es shortest ,8. or longest ,88.
leading pattern, i% thereFs a match

EMparam8patternN

EMparam88patternN
7 remo!es shortest,`. or longest ,`.
trailing pattern, i% match
pattern is e)panded $ust as in pathname
e)pansion ,glo##ing. 7 S, +, 9:
More Parameter )pansion
6ind the length o% a string:

echo EM8%ooN
)tract su#strings

echo EM%oo:2:LN
;ege) search and replace
There are more& See the Bash manpage
)ample 5 Parameter )pansion
! foo#X=i=c
! echo !@fooRS=A
i.c
! echo !@fooRRS=A
c
! echo !@fooE=SA
?.i
! echo !@fooEE=SA
?

You might also like