我试图存储一个条件来比较变量中的值,但它不起作用。我写的代码是:
read op
if [ $op == "desc" ]
then
compare='${arr[0]} -gt ${arr[1]}'
if [ eval "$compare" ]
then
echo "SWAP"
fi
fi
我究竟做错了什么?
编写eval
语句的正确方法是:
if eval [ "$compare" ]
then
...
不要使用变量来存储命令 - 请参阅BashFAQ/050。您可以将代码重写为:
read op
if [ "$op" = "desc" ]; then
if [ "${arr[0]}" -gt "${arr[1]}" ]; then
echo "SWAP"
fi
fi
笔记:
[ ]
中引用变量以防止单词拆分和通配是非常重要的也可以看看:
鉴于代码的作用,不需要eval
,这就足够了:
read op ; [ "$op" = "desc" ] && [ "${arr[0]}" -gt "${arr[1]}" ] && echo "SWAP"
(以上功能相当于codeforester's code。)