5

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 
1
  • 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.CommentedApr 13, 2018 at 23:42

1 Answer 1

12

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.

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.