I have the script below to subtract the counts of files between two directories but the COUNT= expression does not work. What is the correct syntax?
#!/usr/bin/env bash
FIRSTV=`ls -1 | wc -l`
cd ..
SECONDV=`ls -1 | wc -l`
COUNT=expr $FIRSTV-$SECONDV ## -> gives 'command not found' error
echo $COUNT
9 Answers
Try this Bash syntax instead of trying to use an external program expr:
count=$((FIRSTV-SECONDV))
BTW, the correct syntax of using expr is:
count=$(expr $FIRSTV - $SECONDV)
But keep in mind using expr is going to be slower than the internal Bash syntax I provided above.
You just need a little extra whitespace around the minus sign, and backticks:
COUNT=`expr $FIRSTV - $SECONDV`
Be aware of the exit status:
The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.
Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
This is how I always do maths in Bash:
count=$(echo "$FIRSTV - $SECONDV"|bc)
echo $count
White space is important, expr expects its operands and operators as separate arguments. You also have to capture the output. Like this:
COUNT=$(expr $FIRSTV - $SECONDV)
but it's more common to use the builtin arithmetic expansion:
COUNT=$((FIRSTV - SECONDV))
Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:
let COUNT=$FIRSTV-$SECONDV
or
let COUNT=FIRSTV-SECONDV
Diff Real Positive Numbers
diff_real () {
echo "df=($1 - $2); if (df < 0) { df=df* -1}; print df" | bc -l;
}