我试着在Shell脚本中使用以下语法声明一个布尔变量:
variable=$false
variable=$true
这是正确的吗?如果我想要更新那个变量,我会使用相同的语法吗?最后,使用布尔变量作为表达式的以下语法是否正确?
if [ $variable ]
if [ !$variable ]
snapshotEvents=true
if ($snapshotEvents)
then
# Do stuff if true
fi
为了让每个人都满意,我测试了:
snapshotEvents=false
if !($snapshotEvents)
then
# Do stuff if false
fi
这也很好地工作了。
$snapshotEvents
评估变量值的内容。因此,您需要 $
。
您实际上不需要括号,我只是觉得它们有帮助。
测试环境:GNU Bash,版本 4.1.11(2)-release
初学者的Bash指南,Machtelt Garrels,v1.11,2008
DEFINE_bool
例如:DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing");
从命令行可以定义:
sh script.sh --bigmenu
sh script.sh --nobigmenu # False
#!/bin/bash
rounds=100000
b=true # For true; b=false for false
type -a true
time for i in $(seq $rounds); do command $b; done
time for i in $(seq $rounds); do $b; done
time for i in $(seq $rounds); do [ "$b" == true ]; done
time for i in $(seq $rounds); do test "$b" == true; done
time for i in $(seq $rounds); do [[ $b == true ]]; done
b=x; # Or any non-null string for true; b='' for false
time for i in $(seq $rounds); do [ "$b" ]; done
time for i in $(seq $rounds); do [[ $b ]]; done
b=1 # Or any non-zero integer for true; b=0 for false
time for i in $(seq $rounds); do ((b)); done
true is a shell builtin
true is /bin/true
real 0m0,815s
user 0m0,767s
sys 0m0,029s
real 0m0,562s
user 0m0,509s
sys 0m0,022s
real 0m0,829s
user 0m0,782s
sys 0m0,008s
real 0m0,782s
user 0m0,730s
sys 0m0,015s
real 0m0,402s
user 0m0,391s
sys 0m0,006s
real 0m0,668s
user 0m0,633s
sys 0m0,008s
real 0m0,344s
user 0m0,311s
sys 0m0,016s
real 0m0,367s
user 0m0,347s
sys 0m0,017s
#false:
condition=""
#true:
condition=x
#check:
[ -n "${condition}" ]
[[ "$x" == 'true' || "$x" -ne 0 ]] && ...
非常简单,没有依赖关系。
Bash真的让人感到困惑,因为它有像[
、[[
、((
、$((
等等这样的东西。
所有这些都占用了彼此的代码空间。我猜这主要是历史原因,Bash有时必须假装成sh
。
大多数情况下,我可以选择一种方法并坚持使用它。在这种情况下,我倾向于声明(最好是在一个通用库文件中,我可以在我的实际脚本中使用.
包含它)。
TRUE=1; FALSE=0
然后我可以使用 ((
... ))
算术运算符进行测试。
testvar=$FALSE
if [[ -d ${does_directory_exist} ]]
then
testvar=$TRUE;
fi
if (( testvar == TRUE )); then
# Do stuff because the directory does exist
fi
你必须要有纪律性。你的 testvar
必须一直设置为 $TRUE
或者 $FALSE
。
在 ((
... ))
比较中,不需要使用前导符号 $
,这样更易读。
我可以使用 ((
... ))
,因为 $TRUE=1
,$FALSE=0
,即数值。
缺点是有时候需要使用 $
:
testvar=$TRUE
这不太好看。
这不是一个完美的解决方案,但它涵盖了我需要进行此类测试的每种情况。
替代方案 - 使用函数
is_ok(){ :;}
is_ok(){ return 1;}
is_ok && echo "It's OK" || echo "Something's wrong"
定义函数不太直观,但检查其返回值非常容易。
()
不是必需的。但是我的回应是,请尝试一下,这似乎取决于Bash版本、实际表达式或上下文等因素。 - will