2

I am using below script

x=5.44
p=0
temp=$(printf "%.*f\n" $p $x)
echo $temp
if [ temp -gt 0 ]
  then
  echo "inside"
fi

and I am getting below output with error.

5
./temp.sh: line 6: [: temp: integer expression expected
  • 2
    Bash’s built-in printf has a -v option to store the result in a shell variable to avoid the need for command substitution like this. printf -v temp ... is equivalent to temp=$(printf ...) but carries much less overhead than the latter. – David Foerster Apr 13 '18 at 23:42
11

You need to use $ for the shell to expand temp (As your script is written you are trying to compare the literal string temp to the integer 0). You also should quote it:

x=5.44
p=0
temp=$(printf "%.*f\n" $p $x)
echo "$temp"
if [ "$temp" -gt 0 ]
then
  echo "inside"
fi

If you are using bash a better way to do it would be using bash arithmetic expression like so:

x=5.44
p=0
temp=$(printf "%.*f\n" $p $x)
echo "$temp"
if ((temp>0)); then
  echo "inside"
fi

Inside of the arithmetic expression ((…)) you do not need a $ for expansion and you cannot quote.

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.