如何在变量中存储条件并使用eval进行评估?

问题描述 投票:1回答:2

我试图存储一个条件来比较变量中的值,但它不起作用。我写的代码是:

read op
if [ $op == "desc" ]
then
compare='${arr[0]} -gt ${arr[1]}'
if [ eval "$compare" ]
then
 echo "SWAP"
 fi
fi

我究竟做错了什么?

bash shell eval
2个回答
2
投票

编写eval语句的正确方法是:

if eval [ "$compare" ]
then
   ...

不要使用变量来存储命令 - 请参阅BashFAQ/050。您可以将代码重写为:

read op
if [ "$op" = "desc" ]; then
  if [ "${arr[0]}" -gt "${arr[1]}" ]; then
    echo "SWAP"
  fi
fi

笔记:

  • [ ]中引用变量以防止单词拆分和通配是非常重要的
  • 使用shellcheck验证您的代码

也可以看看:


0
投票

鉴于代码的作用,不需要eval,这就足够了:

read op ; [ "$op" = "desc" ] && [ "${arr[0]}" -gt "${arr[1]}" ] && echo "SWAP"

(以上功能相当于codeforester's code。)

© www.soinside.com 2019 - 2024. All rights reserved.