CH24: Scripts Loops Flashcards
(23 cards)
Test []
test command returns:
1 if the test fail
0 if the test succeeds
[paul@RHEL4b ~]$ test 10 -gt 55 ; echo $? 1
how to show TEST[] command results in true / false form
$ test 56 -gt 55 && echo true || echo false
true
$ test 6 -gt 55 && echo true || echo false false
test command can also be written as square brackets
$ [ 56 -gt 55 ] && echo true || echo false
true
$ [ 6 -gt 55 ] && echo true || echo false
false
[ -d foo ]
Does the directory foo exist ?
[ -e bar ]
Does the file bar exist ?
[ ‘/etc’ = $PWD]
Is the string /etc equal to the variable $PWD
[ $1 != ‘secret’ ]
Is the first parameter different from secret
[ 55 -lt $bar ]
Is 55 less than the value of $bar ?
[ $foo -ge 1000 ]
Is the value of $foo greater or equal to 1000 ?
[ “abc” < $bar ]
Does abc sort before the value of $bar ?
[ -f foo ]
Is foo a regular file ?
[ -r bar ]
Is bar a readable file ?
[ foo -nt bar ]
Is file foo newer than file bar ?
[ -o nounset ]
Is the shell option nounset set ?
Tests can be combined with logical AND and OR.
$ [ 66 -gt 55 -a 66 -lt 500 ] && echo true || echo false
true
if then else
#!/bin/bash if [ -f isit.txt ] then echo isit.txt exists! else echo isit.txt not found! fi
tests whether a file exists, and if the file exists then a proper message is echoed.
if then elif
#!/bin/bash count=42 if [ $count -eq 42 ] then echo "42 is correct." elif [ $count -gt 42 ] then echo "Too much." else echo "Not enough." fi
nest a new if inside an else with elif
=———————————-
for loop
for i in 1 2 4
do
echo $i
done
for loop with embedded shell
#!/bin/ksh for counter in `seq 1 20` do echo counting from 1 to 20, now at $counter sleep 1 done
-=-=========——————=====———–===————————==
The same example as above can be written without the embedded shell using the bash {from..to} shorthand.
#!/bin/bash for counter in {1..20} do echo counting from 1 to 20, now at $counter sleep 1 done
for loop uses file globbing
kahlan@solexp11$ ls count.ksh go.ksh
kahlan@solexp11$ for file in *.ksh ; do cp $file $file.backup ; done
kahlan@solexp11$ ls count.ksh count.ksh.backup go.ksh go.ksh.backup
while loop
i=100;
while [ $i -ge 0 ] ; do
echo Counting down, from 100 to 0, now at $i; let i–;
done
Endless loops can be made with while true or while : , where the colon is the equivalent of no operation in the Korn and bash shells.
#!/bin/ksh # endless loop while : do echo hello sleep 1 done
until loop
let i=100; until [ $i -le 0 ] ; do echo Counting down, from 100 to 1, now at $i; let i--; done