[rps-include post=6835]
We can store different type of values in the variables. But just storing values is generally not enough and we need to make some operations with them. In this tutorial we will look different type of operators which will work with variables.
Assignment
The most used operator and generally underestimated its power. Variable assignment is made with =. By the way be aware that you do not confuse assignment operator with test operator which is the same =.
$ a=123 $ echo $a 123
Let Operator
In bash scripting to make mathematical calculations and use operators let expression is used. let expression makes afterward expressions mathematically calculated. Look example below
$ let "z=5" $ echo $z 5
Plus
To make sum operations + is used as expected but be aware of that let should be used.
$ let "a=1" $ let "b=1" $ let "c=a+b" $ echo $c 2
Plus Equal
Plus equal is similar to plus but makes operations easy when one of the sum parameters are same for the result
$ var=12 $ let "var +=5" $ echo $var 17
Minus
Usage usage of the minus operator is the same with plus operator. As you know just the effect is different
$ let "a=1" $ let "b=1" $ let "c=a-b" $ echo $c 0
Minus Equal
Plus equal is similar to plus but makes operations easy when one of the sum parameters are same for the result
$ var=12 $ let "var -=5" $ echo $var 7
Multiplication
You can find the multiplication operation below
$ let "a=1" $ let "b=2" $ let "c=a*b" $ echo $c 2
Simple, isn’t is?
Division
You can find the division operation below
$ let "a=4" $ let "b=2" $ let "c=a/b" $ echo $c 2
Exponentiation
Generally this type of operations are not required in bash scripting but to be aware of this operator we make simple example
$ let "z=5**3" $ echo $z 125
Modulo
To get remainder of a division module is used. For example what will be the remainder after 5/3. We can use following code for this operation. As you will see below we have new keyword named expr
$ expr 5 % 3 2
Bit-wise
Decimal numbers can be expressed in binary format. So if we need to shift the binary values of a decimal Bit-wise operator can be used.
$ var=2 $ let "var<<=2" $ echo $var 8
In this example we have rotated binary for 2 times. Before the rotation binary value was like 0000010. After the rotation it is like 0001000 where its decimal value is 8. We have used = to make assignment easy.
Bit-wise operations can be done in reverse order like >>.
And
Logical operations are important for a programming language. Bash have full support for logical operations like AND.
[rps-include post=6835]
1 thought on “Linux Bash Operators Like Assignment, Plus, Calculation”