12 Compound commands Flashcards
Lists
A list is a sequence of one or more pipelines separated by “;”, “&”, “&&” or “||”, and optionally terminated by one of “;”, “&” or end-of-line. The return value of a list is that of the last command executed in it.
Execute list in a subshell to contain state changes
( ⟨list⟩ ) executes list in a subshell (e.g., to contain state changes)
Group a list to override operator priorities
{ ⟨list⟩ ; } groups a list (to override operator priorities)
For loop
for ⟨variable ⟩ in ⟨words ⟩ ; do ⟨list ⟩ ; done
for f in *.txt ; do cp $f $f.bak ; done
Conditionals
if ⟨list⟩ ; then ⟨list⟩ ; elif ⟨list⟩
then ⟨list⟩ ; else ⟨list⟩ ; fi
While
while ⟨list⟩ ; do ⟨list⟩ ; done until ⟨list⟩ ; do ⟨list⟩ ; done
Ignore next linefeed
single backslash at end of line
case
case ⟨word ⟩ in ⟨pattern⟩|⟨pattern⟩|. . . )
⟨list⟩ ;; …
esac
Matches expanded ⟨word⟩ against each ⟨pattern⟩ in turn (same matching rules as pathname expansion) and executes the corresponding ⟨list⟩ when first match is
found
case "$command" in start) app_server & processid=$! ;; stop) kill $processid ;; *) echo 'unknown command' ;; esac
Boolean tests – inverse logic
[ ] e.g. -e = file exists -d ... = exists + directory ...
String comparisons lexico
⟨string1⟩ == ⟨string2⟩
⟨string1⟩ != ⟨string2⟩
⟨string1⟩ < ⟨string2⟩
⟨string1⟩ > ⟨string2⟩
Aliases allow a string to be substituted for the first word of a command:
$ alias dir=’ls -la’
$ dir
Shell functions
Shell functions are defined with “⟨name⟩ () { ⟨list⟩ ; }”. In the function body, the command-line arguments are available as $1, $2, $3, etc. The variable $* contains all arguments and $# their number.
[unalias dir]
$ dir () { ls -la $* ; }
Function variable access
Outside the body of a function definition, the variables $*, $#, $1, $2, $3, . . . can be used to access the command-line arguments passed to a shell script.