Lui*_*ado 58 bash if-statement
在学习bash的同时,我会看到四种使用if语句的方式:
bash中的Parenthesis和Square Brackets有什么区别.
Gil*_*not 65
您列出的测试:
testtest但功能更强大)并非详尽无遗,您可以使用布尔逻辑
if command; then ...
Run Code Online (Sandbox Code Playgroud)
也是,因为命令具有退出状态.In bash,0is true和> 0是false.
你可以看到这样的退出状态:
command
echo $?
Run Code Online (Sandbox Code Playgroud)
见:
http://wiki.bash-hackers.org/syntax/basicgrammar
http://wiki.bash-hackers.org/syntax/arith_expr
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
shell 本身仅运行命令并评估其退出代码。退出代码为零表示成功;所有其他值均表示失败。
if command; then
: things to do if the exit code from command was 0
else
: things to do if it was not 0
fi
while command; do
: things to do if the exit code was 0
done
Run Code Online (Sandbox Code Playgroud)
命令[(又名test)在条件语句中非常常用,因为原始的 Bourne shell 缺乏内置运算符来检查字符串是否为空或文件是否存在。现代 shell 内置了此命令,并且许多 shell 都有扩展和现代化版本[[,但它不能正确移植到 POSIX sh,因此应避免用于可移植脚本。这个相关问题更详细地解释了两者之间的差异。
该符号(( ... ))引入了算术上下文。同样,这不是原始 Bourne shell 的一部分(它有一个专门的外部工具expr来处理这些事情),但现代 shell 内置了这个功能。如果算术评估的结果是,则算术表达式的结果代码为 0非 0(或错误)。
该符号( command ) 创建一个子 shell 并command在其中进行计算。在某些情况下,这实际上是必要且有用的,但如果您只是学习语法,则不太可能需要它。
...事实上,在大多数脚本中我都看到它在条件中使用,这显然是不必要的。
另一个需要注意的反模式是
command
if [ $? = 0 ]; then
: things
fi
Run Code Online (Sandbox Code Playgroud)
您几乎不需要$?明确检查,特别是,将其与零进行比较是if专门while 为您在幕后做的事情。这应该简单地重构为
if command; then
: ...
Run Code Online (Sandbox Code Playgroud)