CS155 ShellLoops
To loop while a condition is true:
while [[ expr ]] do commands done
To loop over the elements of a list:
for var in list do commands done
% cat beatles #! /bin/bash drummer="Ringo" for musician in John Paul George $drummer do echo "$musician was great!" done % ./beatles John was great! Paul was great! George was great! Ringo was great!
Show the contents of several files:
#! /bin/bash cat $*
Show the contents of several files, with titles:
#! /bin/bash for victim in "$@" do echo "*** $victim" cat $victim done
Remember, "$@"
is the same as "$1" "$2" "$3"
…
The same, but add a file number to each line:
#! /bin/bash let n=0 for victim in "$@" do let n=n+1 echo "*** File #$n: $victim" cat $victim done
If you don’t say what to loop through,
the loop will process "$@"
, which is "$1" "$2" "$3"
…
#! /bin/bash let n=0 for victim do let n=n+1 echo "*** File #$n: $victim" cat $victim done
Now with error checking!
#! /bin/bash if [[ $# -eq 0 ]] then echo "usage: $0 <filenames>" exit 1 fi let n=0 for file do let n=n+1 echo "*** File #$n: $victim" cat $victim done
#! /bin/bash echo "Enter five numbers: " let sum=0 let i=0 while [[ i -lt 5 ]] do read num let sum=sum+num let i=i+1 done echo $sum
#! /bin/bash if [[ $# -eq 0 ]] then echo "usage: $0 <filenames>" exit 1 fi for item do cp $item $item.backup done
What does it do?
#! /bin/bash if [[ $# -eq 0 ]] then echo "usage: $0 <filenames>" exit 1 fi for item do if [[ -e $item ]] then cp $item $item.backup else echo "Can’t back up $item––it doesn’t exist" fi done
Is this any better?