Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

for each iteration, the current value of list is assigned to curvar.


Suppose that you want to create a backup version of each file in a directory to
a subdirectory called backup. You can do the following in pdksh and
bash:


Click here to view code image
#!/bin/sh
for filename in *
do
cp $filename backup/$filename
if [ $? -ne 0 ]; then
echo "copy for $filename failed"
fi
done


In this example, a backup copy of each file is created. If the copy fails, a
message is generated.


The same example in tcsh is as follows:


Click here to view code image
#!/bin/tcsh
foreach filename (/bin/ls)
cp $filename backup/$filename
if ($? != 0) then
echo "copy for $filename failed"
endif
end


The while Statement


You can use the while statement to execute a series of commands while a
specified condition is true. The loop terminates as soon as the specified
condition evaluates to false. It is possible that the loop will not execute at
all if the specified condition initially evaluates to false. You should be
careful with the while command because the loop never terminates if the
specified condition never evaluates to false.


ENDLESS LOOPS   HAVE    A   PLACE   IN  SHELL   PROGRAMS
Endless loops can sometimes be useful. For example, you can easily
construct a simple command that constantly monitors the 802.11 link
quality of a network interface by using a few lines of script:

Click here to view code image
#!/bin/sh

Free download pdf