How to perform arithmetic operations in Bash scripts?

Arithmetic operations can be performed in Bash scripting using the following methods:

  1. Using let command: This command allows you to evaluate arithmetic expressions.
let result=4+6 echo $result # Output: 10
  1. Using double parentheses: You can use double parentheses for arithmetic calculations.
result=$((4 + 6)) echo $result # Output: 10
  1. Using expr command: The expr command evaluates expressions and prints the result.
result=$(expr 4 + 6) echo $result # Output: 10

Note: In expr, the mathematical operators like '+' should be provided as arguments with spaces around them.

  1. Using square brackets: Square brackets can be used for arithmetic expressions.
result=$[4+6] echo $result # Output: 10
  1. Using arithmetic expansion: Arithmetic expansion allows you to perform calculations inside double parentheses.
result=$((4 + 6)) echo $result # Output: 10

It's important to note that these methods only perform integer arithmetic. If you need floating point arithmetic, you can use a tool like bc or awk.

For example, using bc:

result=$(echo "4+6" | bc) echo $result # Output: 10