Jane Wilkie
Jane Wilkie

Reputation: 1743

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

Upvotes: 0

Views: 5082

Answers (4)

Raulillo
Raulillo

Reputation: 316

In case someone has a similar problem even without using the compound command ((..))

Be sure your variables are not defined using let keyword, as it would force shell arithmetic evaluation too.

From the referece:

The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin.

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 34

Another alternative is to pipe the waiting variable through awk to check for a value greater than 3 so:

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

echo $waiting

res=$(echo $waiting | awk '{ if ( $0 > 3 ) print "OK" }')

if [ $res == "OK" ] then (DO SOME STUFF HERE) fi

Upvotes: 0

anubhava
anubhava

Reputation: 785156

It is not recommended to use output of ls to count number of files/directories in a sub -directory as file names may contain newlines or glob characters as well.

Here is one example of doing it safely using gnu find:

dir=/home/inventory
waiting=$(find "$dir" -mindepth 1 -maxdepth 1 -printf '.' | wc -c)

If you don't have gnu find then use:

waiting=$(find "$dir" -mindepth 1 -maxdepth 1 -exec printf '.' \; | wc -c)

Upvotes: 0

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14955

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".

Upvotes: 3

Related Questions