shell 脚本中的布尔变量
Boolean variables in a shell script
我关注这个post
How to declare and use boolean variables in shell script?
并开发了一个简单的 shell 脚本
#!/bin/sh
a=false
if [[ $a ]];
then
echo "a is true"
else
echo "a is false"
fi
输出为
a is true
怎么了?
您需要检查值是否等于 true
,而不仅仅是变量是否已设置。尝试以下操作:
if [[ $a = true ]];
这不起作用,因为 [[
仅测试变量是否为空。
你需要写:
if [[ $a = true ]];
而不仅仅是
if [[ $a ]];
注意true
和false
实际上是commands in bash,所以你可以省略条件括号然后做:
if $a;
更新:阅读this excellent answer后,我撤销此建议。
if [[ $a ]]
没有像您预期的那样工作的原因是当 [[
命令仅接收一个参数(除了结束 ]]
之外)时,return 如果参数非空,则值为成功。显然字符串 "false" 不是空字符串。参见 https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs and https://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions
我关注这个post How to declare and use boolean variables in shell script?
并开发了一个简单的 shell 脚本
#!/bin/sh
a=false
if [[ $a ]];
then
echo "a is true"
else
echo "a is false"
fi
输出为
a is true
怎么了?
您需要检查值是否等于 true
,而不仅仅是变量是否已设置。尝试以下操作:
if [[ $a = true ]];
这不起作用,因为 [[
仅测试变量是否为空。
你需要写:
if [[ $a = true ]];
而不仅仅是
if [[ $a ]];
注意true
和false
实际上是commands in bash,所以你可以省略条件括号然后做:
if $a;
更新:阅读this excellent answer后,我撤销此建议。
if [[ $a ]]
没有像您预期的那样工作的原因是当 [[
命令仅接收一个参数(除了结束 ]]
之外)时,return 如果参数非空,则值为成功。显然字符串 "false" 不是空字符串。参见 https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs and https://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions