Bash布尔表达式及其值分配 [英] Bash boolean expression and its value assignment
问题描述
有没有一种方法可以评估布尔表达式并将其值分配给变量?
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
我希望以类似的方式在bash中进行评估:
I want similar way to evaluate in bash:
BOOL=[ "$PROCEED" -ne "y" ] ;
这无法正常工作,并尝试了其他方法,但无法获得布尔值.有没有办法 不用IF就能做到吗?
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 ?
推荐答案
您可以这样做:
[ "$PROCEED" = "y" ] ; BOOL=$?
如果您正在使用set -e
,则可以改用:
If you're working with set -e
, you can use instead:
[ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1
BOOL
在存在匹配项时设置为零,以像典型的Unix返回码一样工作.看起来有点怪.
BOOL
set to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.
这不会引发错误,并且您确定$BOOL
之后将为0或1,无论之前包含什么.
This will not throw errors, and you're sure $BOOL
will be either 0 or 1 afterwards, whatever it contained before.
这篇关于Bash布尔表达式及其值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!