Search code examples
bashvariablesscripting

Bash error: Division on zero error when using directory path


I'm writing a bash script that checks the number of files in a directory and if it's over a certain number, do something. The code is here:

DIR=/home/inventory
waiting="$((ls ${DIR}/waiting/ -1 | wc -l))"

echo $waiting

if [ $waiting -gt 3 ]
   then
     (DO SOME STUFF HERE)
fi

The error I am getting is this line....

waiting="$((ls ${DIR}/waiting/ -1 | wc -l))"

Specifically the error is ....

division by 0 (error token is "/home/inventory/waiting/ -1 | wc -l")

I thought trying to put the number of files in this directory into a variable would work using $(()).

Does anyone have an idea why this is failing? Many TIA..... Jane


Solution

  • Use single parenthesis:

    waiting="$(ls ${DIR}/waiting/ -1 | wc -l)"
    

    $(( ... )) is used to perform arithmetic calculations.

    From the man page:

    ((expression))

    The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression".