Выбрать главу

So if you wanted to print "Too high!" if the value of the variable A was over 50, you would write:

if test "$A" -gt 50

then

 echo "Too high!"

fi

The variable expression $A is quoted in case A has a null value ("") or doesn't existin which case, if unquoted, a syntax error would occur because there would be nothing to the left of -gt .

The square brackets ( [] ) are a synonym for test , so the previous code is more commonly written:

if [ "$A" -gt 50 ]

then

 echo "Too high!"

fi

You can also use test with the while control structure. This loop monitors the number of users logged in, checking every 15 seconds until the number of users is equal to or greater than 100, when the loop will exit and the following pipeline will send an email to the email alias alert :

while [ "$(who | wc -l)" -lt 100 ]

do

 sleep 15

done

echo "Over 100 users are now logged in!"|mail -s "Overload!" alert

4.12.1.4. Integer arithmetic

bash provides very limited integer arithmetic capabilities. An expression inside double parentheses (( )) is interpreted as a numeric expression; an expression inside double parentheses preceded by a dollar sign $(( )) is interpreted as a numeric expression that also returns a value.

Inside double parentheses, you can read a variable's value without using the dollar sign (use A=B+C instead of A=$B+$C). 

Here's an example using a while loop that counts from 1 to 20 using integer arithmetic:

A=0

while [ "$A" -lt 20 ]

do

 (( A=A+1 ))

 echo $A

done

The C-style increment operators are available, so this code could be rewritten as:

A=0

while [ "$A" -lt 20 ]

do

 echo $(( ++A ))

done

The expression $(( ++A )) returns the value of A after it is incremented. You could also use $(( A++ )) , which returns the value of A before it is incremented:

A=1

while [ "$A" -le 20 ]

do

 echo $(( A++ ))

done

Since loops that count through a range of numbers are often needed, bash also supports the C-style for loop. Inside double parentheses, specify an initial expression, a conditional expression, and a per-loop expression, separated by semicolons:

# Initial value of A is 1

# Keep looping as long as A<=20

# Each time you loop, increment A by 1

for ((A=1; A<=20; A++))

do

 echo $A

done

Note that the conditional expression uses normal comparison symbols ( <= ) instead of the alphabetic options ( -le ) used by test .