Working with Shell Arithmetic and Boolean Operators in Unix:
In this tutorial, we will review the various operators that are supported by the Unix shell.
Operators are used for manipulating variables and constants in shell programs. They are required to perform mathematical operations.
Here, we will explain to you more about working with Arithmetic Operators.
Unix Video #14:
Note that the back-tick (`) is often used here – when executing a command, everything between the back-ticks is executed and substituted with the result before the remainder of the command is executed.
In newer shells (Example: bash), the same result can be achieved by embedding the expression between ‘$(’ and ‘)’.
Operators in Unix
#1) Shell Arithmetic Operators Example
These consist of basic mathematical operations:
- Addition: +
- Subtraction: –
- Multiplication: *
- Division: /
- Modulus: %
Each of these operators performs the operation on two integer variables or constants.
For Example, the below program illustrates each of these operations:
$ c=`expr $a + $b` $ echo “the value of addition=$c” $ d=`expr $a - $b` $ echo “the value of subtraction=$d” $ e= expr $a \* $b` $ echo “the value of multiplication=$e” $ f=`expr $a / $b` $ echo “the value of division=$f” $ g= echo `expr $a % $b` $ echo “the value of modulus=$c”
The Unix shell does not natively support floating point operations. A separate command-line tool must be used for this. The ‘bc’ co0mmand is the most standard tool for this.
Example:
$ c = `echo “$a + $b” | bc` $ d = `echo “$a + $b” | bc`
Note that each of the operators needs to be surrounded by a space on both sides, and the ‘*’ operators need to be escaped with a backslash ‘\’.
#2) Shell Logical Boolean Operators Example
The logical operators in Unix are as follows:
- Not:!
- And: -a
- Or: -o
These operators and their usage will be covered in detail in the next tutorial.