In the last chapter, you learned about debugging, the here operator, interactive Shell scripts for taking input from the keyboard, and file handling.
In this chapter, we will cover the following arithmetic operations topics:
We can perform arithmetic operations in various ways, such as using declare, let, expr, and arithmetic expressions. You will also learn about representing numbers in different bases, such as binary, octal, and hex.
Whenever we declare any variable, by default, this variable stores the string type of data. We cannot do arithmetic operations on them. We can declare a variable as an integer by using the declare command. Such variables are declared as integers; if we try to assign a string to them, then bash assigns 0 in these variables.
Bash will report an error if we try to assign fractional values (floating points) to integer variables.
We can create an integer variable called value, shown as follows:
$ declare –i value
We tell the shell that the variable value is of type integer. Otherwise, shell treats all variables as character strings:
name string to the integer variable value, then the value variable will be assigned the 0 value by Bash shell:$ value=name $ echo $value 0
$ value=4 + 4 bash: +: command not found
$ value=4+4 $ echo $value 8
$ value=4*3 $ echo $value 12 $ value="4 * 5" $ echo $value 20
"", the multiplication operation is performed. Due to double quotes (""), the * operator was not used as a wildcard (*):$ value=5.6 bash: num: 5.6: syntax error in expression (remainder of expression is ".5").
Since we have declared the variable value as an integer variable, when we initialize the variable with a floating point number, the error gets displayed by Bash shell.
If we want to see all declared integer variables along with their values, then we must give the following command:
$ declare –i
Output:
declare -ir BASHPID="" declare -ir EUID="1001" declare -i HISTCMD="" declare -i LINENO="" declare -i MAILCHECK="60" declare -i OPTIND="1" declare -ir PPID="1966" declare -i RANDOM="" declare -ir UID="1001"