The first thing wrong is your assignment to dl
:
dl="$downloadspeed/1" | bc
This means "set the variable $dl
to the string 800.00/1
, and then pass the output of the variable assignment to bc
". Since the assignment has no output, the result is just setting dl
to 800.00
.
BUT, and this is important, pipelines run in their own subshell and any variables set in that subshell won't be available to the parent shell. This means that even if this assignment were actually doing what you wanted it to do, dl
would still only be set while that pipeline is running and would be unset in the script itself.
Then, you run this:
if [ $((dl)) -lt 500 ]
This means "if the result of executing the contents of the $dl
variable as an arithmetic expression command are less than 500. To do this, you need to set the value of dl
to a valid arithmetic expression. For example:
800/1
But what you have is an empty variable since, as mentioned above, the $dl
only had a value in the subshell running the pipe.
In any case, this is all really needlessly complicated. Why not do this instead:
#!/bin/sh
downloadspeed=800.00
value=$(printf '%s\n' "$downloadspeed"/1 | bc)
if [ $value -lt 500 ]
then
echo "slow - send slow message"
else
echo "fast - no issue"
fi
Next time, to debug such issues, you can use set -x
. Add it to the start of your script:
#!/bin/sh
set -x
downloadspeed=800.00
dl="$downloadspeed/1" | bc
if [ $((dl)) -lt 500 ]
then
echo "slow - send slow message"
else
echo "fast - no issue"
fi
if you now run your script, you will see exactly what commands are being executed:
$ foo.sh
+ downloadspeed=800.00
+ dl=800.00/1
+ bc
+ '[' 0 -lt 500 ']'
+ echo 'slow - send slow message'
slow - send slow message
As you can see, because $dl
is empty but is used inside an arithmetic expression ($(( ))
), that is evaluated to 0, and you're actually running [ 0 -lt 500 ]
, which is always true.