Читать книгу Linux Bible - Christopher Negus - Страница 204

Performing arithmetic in shell scripts

Оглавление

Bash uses untyped variables, meaning it normally treats variables as strings of text, but you can change them on the fly if you want it to.

Bash uses untyped variables, meaning that you are not required to specify whether a variable is text or numbers. It normally treats variables as strings of text, so unless you tell it otherwise with declare, your variables are just a bunch of letters to bash. However, when you start trying to do arithmetic with them, bash converts them to integers if it can. This makes it possible to do some fairly complex arithmetic in bash.

Integer arithmetic can be performed using the built-in let command or through the external expr or bc commands. After setting the variable BIGNUM value to 1024, the three commands that follow would all store the value 64 in the RESULT variable. The bc command is a calculator application that is available in most Linux distributions. The last command gets a random number between 0 and 10 and echoes the results back to you.

 BIGNUM=1024 let RESULT=$BIGNUM/16 RESULT=`expr $BIGNUM / 16` RESULT=`echo "$BIGNUM / 16" | bc` let foo=$RANDOM; echo $foo

Another way to grow a variable incrementally is to use $(()) notation with ++I added to increment the value of I. Try typing the following:

 $ I=0 $ echo "The value of I after increment is $((++I))" The value of I after increment is 1 $ echo "The value of I before and after increment is $((I++)) and $I" The value of I before and after increment is 1 and 2

Repeat either of those commands to continue to increment the value of $I.

Linux Bible

Подняться наверх