lecture 5 more about shell script. script example task: write a script that accepts an optional...
TRANSCRIPT
Lecture 5Lecture 5
More about Shell ScriptMore about Shell Script
Script ExampleScript Example
Task: Write a script that accepts an Task: Write a script that accepts an optional command line parameter – a optional command line parameter – a directory name and prints the file system directory name and prints the file system structure under this directory in the form of structure under this directory in the form of a tree. Without parameters, it should start a tree. Without parameters, it should start in the current directory. Call this script in the current directory. Call this script dirtree.cshdirtree.csh
Example Result of dirtree.cshExample Result of dirtree.csh % dirtree% dirtree|||------bin|------bin| || || |------.garbage| |------.garbage| | || | || | |------file1| | |------file1| | | | | |------examples| |------examples| | || | || | |------arg| | |------arg| | |------average.csh| | |------average.csh| | |------fileinfo.csh| | |------fileinfo.csh| | | | | |------hw6.sh| |------hw6.sh| |------lab3| |------lab3
Script: dirtree.cshScript: dirtree.csh#!/bin/csh -f#!/bin/csh -f
if($#argv == 0) thenif($#argv == 0) then set thisdir="."set thisdir="."elseelse set thisdir=$argv[1]set thisdir=$argv[1]endifendif
if($?TREEPREFIX) thenif($?TREEPREFIX) then set prefix="$TREEPREFIX"set prefix="$TREEPREFIX"elseelse set prefix=""set prefix=""endifendifecho "$prefix|"echo "$prefix|"
set filelist=`ls -A $thisdir` set filelist=`ls -A $thisdir` foreach file ($filelist)foreach file ($filelist) echo "${prefix}|------${file}"echo "${prefix}|------${file}" if(-d "$thisdir/$file") thenif(-d "$thisdir/$file") then
if($file == $filelist[$#filelist]) if($file == $filelist[$#filelist]) thenthen
setenv TREEPREFIX setenv TREEPREFIX "${prefix} ""${prefix} "
elseelse setenv TREEPREFIX setenv TREEPREFIX
"${prefix}| ""${prefix}| " endifendif
$0 "$thisdir/$file"$0 "$thisdir/$file" endifendifendendecho "$prefix"echo "$prefix"
More on ConditionalsMore on Conditionals
Recall the if commandRecall the if command
if ( expression ) thenif ( expression ) thencommandcommand
endifendif expression must be an actual boolean expression must be an actual boolean
expressionexpression -d directory-d directory $x > $y$x > $y
More on ConditionalsMore on Conditionals
Problem: we want an expression like: “execute Problem: we want an expression like: “execute a command cmd and then do something based a command cmd and then do something based on the exit status of the command”?on the exit status of the command”?
Solution: store status of cmd in variableSolution: store status of cmd in variableset exitStatus = cmdset exitStatus = cmdif ($exitStatus == 0) thenif ($exitStatus == 0) then
……
else if ($exitStatus == 1) thenelse if ($exitStatus == 1) then……
……endifendif
The Status VariableThe Status Variable
We don’t actually have to assign the exit status We don’t actually have to assign the exit status to a variable. The shell does this for us.to a variable. The shell does this for us.
$status is the exit status of the last command $status is the exit status of the last command executedexecuted
cmdcmdif ($status == 0) thenif ($status == 0) then
……
else if ($status == 1) thenelse if ($status == 1) then……
……endifendif
A ShortcutA Shortcut
If we only care about whether cmd exited If we only care about whether cmd exited successfully or not, we don’t even need to successfully or not, we don’t even need to use the $status variableuse the $status variable
if { ( cmd ) } thenif { ( cmd ) } then......
elseelse……
endifendif
Evaluating CommandsEvaluating Commands
Surround the command with { ( ) }Surround the command with { ( ) }if { ( cmd ) }if { ( cmd ) }
Evaluates to true iff exit status of cmd is 0Evaluates to true iff exit status of cmd is 0
Script Exit StatusScript Exit Status
How do we return an exit status for our How do we return an exit status for our scripts?scripts?
Use the exit commandUse the exit command exit 0, exit 1, etc.exit 0, exit 1, etc.
Convention is the exit status of 0 means Convention is the exit status of 0 means normal exit and any other exit status normal exit and any other exit status means abnormal exitmeans abnormal exit
Conditional StructuresConditional Structures
We have already seen if. There is also switch.We have already seen if. There is also switch.
switch ( value )switch ( value )
case constant1:case constant1:commands …commands …
breakswbreaksw
case constant2:case constant2:
breakswbreaksw
…………………… ……………………..
endswendsw
Notes on SwitchNotes on Switch
If a variable is used as the value, surround If a variable is used as the value, surround the variable with double quotesthe variable with double quotes
switch ( “$status” )switch ( “$status” ) Fall through is allowedFall through is allowed
case 1:case 1:case 2:case 2:
echo “1 or 2”echo “1 or 2”breakbreak
Default case is allowedDefault case is allowed
More on Looping StructuresMore on Looping Structures
Loops can be nestedLoops can be nested break stops execution of the current break stops execution of the current
innermost loopinnermost loop continue begins the next iteration of the continue begins the next iteration of the
current innermost loopcurrent innermost loop Another loop!Another loop!
repeat repeat
Repeat CommandRepeat Command repeat number commandrepeat number command
repeat 3 echo hellorepeat 3 echo hello repeat can be used to break out of more than repeat can be used to break out of more than
one loopone loopwhile ( $x > y )while ( $x > y )
……while ( $a > $b )while ( $a > $b )
……if ( $c == 1 ) thenif ( $c == 1 ) then
repeat 2 breakrepeat 2 breakendifendif
endend
endend
Interrupt HandlingInterrupt Handling
When a script is executing and an interrupt When a script is executing and an interrupt (Ctrl-c) occurs, the script exits(Ctrl-c) occurs, the script exits
Use the onintr command to do something Use the onintr command to do something (like clean up temporary files) before (like clean up temporary files) before exitingexiting onintr labelonintr label
• jump to label and execute commands therejump to label and execute commands there onintr –onintr –
• ignore interruptsignore interrupts
Onintr ExampleOnintr Example
onintr cleanuponintr cleanup
script body goes herescript body goes here
cleanup:cleanup:
onintr –onintr –
clean up code goes hereclean up code goes here
Pros and Cons of Shell ScriptingPros and Cons of Shell Scripting Quick programming solutions for simple Quick programming solutions for simple
problemsproblems Shell is an interpreter (no compilation Shell is an interpreter (no compilation
compared with C)compared with C) Programming difficult things in shell is an Programming difficult things in shell is an
abuse and ends up clumsyabuse and ends up clumsy Compared with C, shell doesn’t allow Compared with C, shell doesn’t allow
subroutines and functionssubroutines and functions No complete data typesNo complete data types
Seeking the Right SolutionsSeeking the Right Solutions With increasing complexity of problems, With increasing complexity of problems,
solutions are: shell script solutions are: shell script PerlPerlCC Perl stands for Practical Extractions and Perl stands for Practical Extractions and
Report LanguageReport Language Retain the immediateness of shell script while Retain the immediateness of shell script while
having the flexibility of Chaving the flexibility of C Extremely good for text file handlingExtremely good for text file handling
CC Full fledged programming languageFull fledged programming language
Recommended ReadingRecommended Reading
Chapter 10Chapter 10
ReviewReview
Something Fun!!Something Fun!! http://csscreator.com/node/11122