CS155 ShellLoops
while [[ expr ]] do commands done
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?
Modified: 2017-02-11T21:00 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |