Bash 布尔表达式及其赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9906041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:52:14  来源:igfitidea点击:

Bash boolean expression and its value assignment

bash

提问by sakhunzai

Is there a way to to evaluate a boolean expression and assign its value to a variable?

有没有办法评估布尔表达式并将其值分配给变量?

In most of the scripting languages there is way to evaluates e.g

在大多数脚本语言中,都有评估的方法,例如

//PHS
$found= $count > 0 ;  //evaluates to a boolean values

I want similar way to evaluate in bash:

我想要类似的方式在 bash 中进行评估:

BOOL=[ "$PROCEED" -ne  "y" ] ; 

This is not working and tried other way but could not get a boolean value. IS there a way to do this WITHOUT using IF ?

这不起作用并尝试了其他方式,但无法获得布尔值。有没有办法在不使用 IF 的情况下做到这一点?

回答by Mat

You could do:

你可以这样做:

[ "$PROCEED" = "y" ] ; BOOL=$?

If you're working with set -e, you can use instead:

如果您正在使用set -e,则可以改用:

[ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1

BOOLset to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.

BOOL匹配时设置为零,以类似于典型的 Unix 返回码。看起来有点奇怪。

This will not throw errors, and you're sure $BOOLwill be either 0 or 1 afterwards, whatever it contained before.

这不会抛出错误,并且您确定之后$BOOL将是 0 或 1,无论它之前包含什么。

回答by Andrew

I would suggest:

我会建议:

[ "$PROCEED" = "y" ] || BOOL=1

This has the advantage over checking $?that it works even when set -eis on. (See writing robust shell scripts.)

这比检查$?它是否工作更有优势,即使在set -e打开时也是如此。(请参阅编写健壮的 shell 脚本。)

回答by user11023646

Rather than using ... && BOOL=0 || BOOL=1suggested in the currently-accepted answer, it's clearer to use trueand false.

与使用... && BOOL=0 || BOOL=1当前接受的答案中的建议相比,使用trueand更清晰false

And since this question is about bash specifically (not POSIX shell), it's also better to use [[instead of [(see e.g. 1and 2), which allows using ==instead of =.

而且由于这个问题特别是关于 bash(而不是 POSIX shell),所以最好使用[[而不是[(参见例如12),它允许使用==代替=.

So if you had to use a one-liner for something like this in bash, the following would be better:

因此,如果您必须在 bash 中为这样的事情使用单行,以下内容会更好:

[[ "$PROCEED" == "y" ]] && should_proceed=true || should_proceed=false

[[ "$PROCEED" == "y" ]] && should_proceed=true || should_proceed=false

Then you can use the derived variable ergonomically in boolean contexts...

然后您可以在布尔上下文中以符合人体工程学的方式使用派生变量...

if $should_proceed; then
  echo "Proceeding..."
fi

...including with the !operator:

...包括!运营商:

if ! $should_proceed; then
  echo "Bye for now."
  exit 0
fi

回答by user unknown

Assignment:

任务:

found=$((count > 0))