While working in bash or while writing bash scripts, many times it so happens we rely on external commands to get our math done. Most of the arithmetic can be handled by the bash itself. In this article, we will see how to do arithmetic operations in bash.
1. Add / Subtract numbers:
One common way to basic arithmetic using bash is by using the let command.
x=20 y=30 let z=x+y echo "z is $z"This is purely a shell operation without any external command. This way one can do for subtract(/), multiply(*), divide(/) and remainder(%) operation.
x=20 y=30 ((z=x+y)) echo "z is $z"The other way to do is using the ((expression)) where the expression is an arithmetic one. Using this double brace notation, all the bash arithmetic can be done.
Bash also allows to use +=, -= operators like in many programming languages. So, if we have something like x=x+10, it can be written as
x=40 ((x+=10)) echo "x is $x"2. Unary operator:
Bash has the unary operator ++ and -- . In the below example, the value of x is being incremented by 1. It is equivalent to writing x=x+1.
x=40 ((x++)) echo "x is $x"3. Conditional:
Bash has a C program like syntax when it comes for condition checking using if block.
x=20 y=30 if (( x > y )) then echo "$x is bigger" else echo "$y is bigger" fiIf you notice above, we did not use $ infront of the variables x or y. Within the bracket notations, we refer to the variable directly.
4. Logical Operator:
Bash provides both the logical AND and logical OR like other programming languages.
x=20 y=30 if ((x > 10)) && (( x > y )) then echo "x is bigger" else echo "y is bigger" fiWe are comparing more than one condition here using logical &&. The condition will be true only when both the condition are true. Similarly, for logical OR, we use ||.
5. Ternary operator:
Bash has an exact C like ternary operator too.
x=40 y=50 ((z=(x>y)?100:200)) echo $zIf x is greater than y, 100 is assigned to z, else 200 is assigned.
Note: Bash does not support floating point operations. To deal with floating point arithmetic, we can make use of the bc command.
No comments:
Post a Comment