CS计算机代考程序代写 CS246-F20-01-UnixShell

CS246-F20-01-UnixShell

Lecture 1.16

• Writing bash scripts
– while, for, break, continue

CS246

while

• Again, two syntaxes (prefer the first):

while ; do

done

while
do


done

• testCommand is evaluated; exit status of zero implies true,
otherwise false

• for is a specialized while stmt for iterating with an index over list of strings
– If no “in list”, iterate over quoted parameters, i.e., “${@}”

for index [ in list ] ; do
commands

done

• Examples:
for name in ric peter jo mike ; do

echo ${name}
done

for arg in “${@}” ; do # process params, why quotes?
echo ${arg}

done

for

• Can also iterate over a set of values:
# note double parentheses
for (( init-expr; test-expr; incr-expr )); do

commands
done

• Example:
for (( i = 1; i <= ${#}; i += 1 )); do eval echo "\${${i}}" # ${1-#} done • Can also use for directly on command line: $ for file in *.cc; do cp "${file}" "${file}".old; done for • A while/for loop may contain break and continue to terminate loop, or advance to the next loop iteration. # process files data1, data2, … declare –i i i=0 while [ 0 ] ; do # Note infinite loop i+=1 file=data${i} # create file name # file not exist, stop ? if [ ! -f "${file}" ] ; then break ; fi … # if ok, process file # bad return, abort this one and go to next file if [ ${?} -ne 0 ] ; then continue ; fi … # process file done break, continue break, continue • In case you didn't know: – break means "abort the loop altogether; carry on executing after the end of the loop" – continue means "abort the current loop iteration, but carry on with the next iteration back at the beginning of the loop" End CS246