语法错误:“应为整数表达式”

Avi*_*ani 4 shell bash shell-script

我正在使用以下脚本

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

我得到低于输出的错误。

5
./temp.sh: line 6: [: temp: integer expression expected
Run Code Online (Sandbox Code Playgroud)

jes*_*e_b 11

您需要使用$shell 来扩展 temp (在编写脚本时,您正在尝试将文字字符串temp与整数进行比较0)。你也应该引用它:

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

如果您使用 bash 更好的方法是使用 bash 算术表达式,如下所示:

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

在算术表达式中,((…))您不需要$用于扩展并且不能引用。