2

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
  • Check the placement of your parantheses. – schaiba Feb 16 '17 at 12:34
9

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`
6

Arithmetic expansion is done by bash and some other shells with $(( ... )), e.g.

line_count=$(( line_count/3 ))

With line_count=$(line_count)/3, you are assigning the output of the command line_count to the variable line_count, suffixed by /3.

This is why you get the error "line_count: command not found" and then the output /3.

Have a look at ShellCheck at https://www.shellcheck.net/ It is able to check you script for common issues. In this case, it won't help you with spotting that $(...) should have been $((...)) but that's because $(line_count) is perfectly legal shell code. It just does the wrong thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.