Bash – Arithmetic syntax in bash

arithmeticbashshell-script

I am getting the below error on arithmetic values

#!/bin/bash
n=0
line_count=9
line_count=$(line_count)/3
echo $line_count
exit 0

expected result is 3

[]$ ./test.sh
./test.sh: line 4: line_count: command not found
/3
[]$ more test.sh

Best Answer

To complement @Kusalananda's answer, in addition to the standard sh syntax:

line_count=$((line_count / 3))

In bash you can also use these syntaxes inherited from ksh (also work in zsh):

  • ((line_count = line_count / 3))
  • ((line_count /= 3))
  • let line_count/=3
  • typeset -i line_count; line_count=line_count/3

bash (and zsh) also support:

  • line_count=$[line_count/3]

For old pre-POSIX Bourne/Almquist sh:

line_count=`expr "$line_count" / 3`
Related Question