bash/sh if 语句语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3430529/
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
bash/sh if statement syntax
提问by Jacob Rask
In various guides and scripts I come across people tend to use different syntax of if statements. What's the difference and what are best practices? I believe all the following statements, and many more variants, will return true:
在我遇到的各种指南和脚本中,人们倾向于使用不同的 if 语句语法。有什么区别,最佳实践是什么?我相信以下所有陈述以及更多变体都会返回 true:
bar="foo"
if [ "foo" = "foo" ]
if [[ "foo" == $bar ]]
if [ "foo" = "$bar" ]
if [[ "foo" = "$bar" ]]
if [[ "foo" -eq $bar ]]
采纳答案by lucas1000001
As I understand it
据我了解
= expects strings
= 期望字符串
-eq expects integers
-eq 需要整数
"$bar" is for literal matches, i.e. z* may expand but "z*" will literally match the wildcard char.
"$bar" 用于字面匹配,即 z* 可以扩展但 "z*" 将字面匹配通配符字符。
The difference between [] and [[]] is that in the latter word splitting and path name expansion are not done, but are in the former.
[] 和 [[]] 的区别在于,在后者中没有进行分词和路径名扩展,而是在前者中。
Plus [[]] allows the additional operators :
加上 [[]] 允许额外的运算符:
&& (AND), || (OR), > (String1 lexically greater than String2), < (String1 lexically less than String2)
&& (AND), || (OR), > (String1 在词法上大于 String2), < (String1 在词法上小于 String2)
The == comparison operator behaves differently within a double-brackets test than within single brackets.
== 比较运算符在双括号测试中的行为与在单括号中的行为不同。
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == z* ]] # 如果 $a 以“z”开头(模式匹配),则为真。
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[[ $a == "z*" ]] # 如果 $a 等于 z*(字面匹配)则为真。
[ $a == z* ] # File globbing and word splitting take place.
[ $a == z* ] # 文件通配和分词发生。
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
[ "$a" == "z*" ] # 如果 $a 等于 z*(字面匹配)则为真。
Check out http://tldp.org/LDP/abs/html/comparison-ops.htmlfor more info
回答by Philipp
[is a bash builtin, [[is a bash keyword. Best practice is to always use [[if the script doesn't have to be compatible with other shells (e.g., if it starts with #!/bin/bash), and use [only for compatibility with the Bourne shell. See http://mywiki.wooledge.org/BashFAQ/031.
[是一个内置的 bash,[[是一个 bash 关键字。最佳实践是,[[如果脚本不必与其他 shell 兼容(例如,如果它以 开头#!/bin/bash),则始终使用,并且[仅用于与 Bourne shell 兼容。请参阅http://mywiki.wooledge.org/BashFAQ/031。
回答by ghostdog74
I recommend case/esac.
我推荐案例/esac。
case "$foo" in
"bar" ) echo "bar";;
*) echo "not equal";;
esac
No fretting about different syntax.
不用担心不同的语法。

