shell 脚本中条件语句的不同类型大括号有哪些不同用途?
我知道至少有 4 种在 shell 脚本中测试条件的方法。
- <代码>[ <条件>; ];
[[
; ]]; ((
)); test
;
我想全面了解这些之间的区别方法是什么,以及何时使用哪种方法。
我尝试在网上搜索摘要,但没有找到任何合适的内容。如果能在某个地方有一个像样的列表就太好了(堆栈溢出来救援!)。
I know of at least of 4 ways to test conditions in shell scripts.
[ <cond> ];
[[ <cond> ]];
(( <cond> ));
test <cond>;
I would like to have a comprehensive overview of what the differences between these methods are, and also when to use which of the methods.
I've tried searching the web for an summary but didn't find anything decent. It'd be great to have a decent list up somewhere (stack overflow to the rescue!).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们在这里描述一下它们。
首先,基本上有3种不同的测试方法
[ EXPRESSION ]
,这与test EXPRESSION
完全相同[[ EXPRESSION ]]
let "EXPRESSION"
完全相同,让我们详细介绍一下:
test
这是测试命令的鼻祖。即使您的 shell 不支持它,几乎每个 UNIX 系统上仍然有一个
/usr/bin/test
命令。因此,调用test
将运行内置程序或二进制文件作为后备。输入$ type test
查看使用的是哪个版本。对于[
也是如此。在大多数基本情况下,这应该足以进行测试。
如果您需要更多功能,那么还有...
[[]]
这是一个 bash 特别版。并非每个 shell 都需要支持这一点,并且没有二进制回退。它提供了更强大的比较引擎,特别是模式匹配以及正则表达式匹配。
(())
这是一个用于算术表达式的 bash 特殊函数,如果计算结果非零则为 true。并非每个 shell 都需要支持这一点,并且没有二进制回退。
请注意,在
(( ... ))
或let
中引用变量时,可以省略$
符号。Let's describe them here.
First of all, there are basically 3 different test methods
[ EXPRESSION ]
, which is exactly the same astest EXPRESSION
[[ EXPRESSION ]]
(( EXPRESSION ))
, which is exactly the same aslet "EXPRESSION"
Let's go into the details:
test
This is the grandfather of test commands. Even if your shell does not support it, there's still a
/usr/bin/test
command on virtually every unix system. So callingtest
will either run the built-in or the binary as a fallback. Enter$ type test
to see which version is used. Likewise for[
.In most basic cases, this should be sufficient to do your testing.
If you need more power, then there's...
[[]]
This is a bash special. Not every shell needs to support this, and there's no binary fallback. It provides a more powerful comparison engine, notably pattern matching and regular expression matching.
(())
This is a bash special used for arithmetic expressions, and is true if the result of the calculation is non-zero. Not every shell needs to support this, and there's no binary fallback.
Note that you can omit the
$
sign when referencing variables within(( ... ))
orlet
.在此处链接的网站上,如果向下滚动到
[
特殊字符,您将看到[[
的单独条目,其中包含讨论它们之间差异的链接。下面还有一个((
的条目。希望有帮助!On the site linked here, if you scroll down to the
[
special character, you will see a separate entry for[[
, with a link to the discussion of the differences between them. There is also an entry for((
below those. Hope that helps!