我对Bash中方括号、圆括号、花括号的用法以及它们的双形式和单形式之间的区别感到困惑。有明确的解释吗?
当前回答
关于如何使用括号对表达式进行分组和展开的其他信息: (它列在链接语法括号中)
这里有一些要点:
在子shell中分组命令:() (列表)
将当前shell中的命令分组:{} {列表;}
Test -返回一个表达式的二进制结果:[[]] [表达式]]
算术扩张 算术展开的格式是: $(表达式)
简单算术求值的格式是: (表达)
组合多个表达式 (表达式) (expr1 && expr2))
其他回答
test,[和[]之间的区别在BashFAQ中有详细的解释。 (注:链接中有很多例子供比较)
To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[. [[ is a new, improved version of it, and it is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.
结论是:
什么时候使用新的测试命令[[,什么时候使用旧的测试命令[? 如果要考虑到POSIX或BourneShell的可移植性/一致性,则应该考虑旧语法 被使用。如果脚本需要BASH、Zsh或KornShell, 新的语法通常更加灵活。
关于如何使用括号对表达式进行分组和展开的其他信息: (它列在链接语法括号中)
这里有一些要点:
在子shell中分组命令:() (列表)
将当前shell中的命令分组:{} {列表;}
Test -返回一个表达式的二进制结果:[[]] [表达式]]
算术扩张 算术展开的格式是: $(表达式)
简单算术求值的格式是: (表达)
组合多个表达式 (表达式) (expr1 && expr2))
括号
if [ CONDITION ] Test construct
if [[ CONDITION ]] Extended test construct
Array[1]=element1 Array initialization
[a-z] Range of characters within a Regular Expression
$[ expression ] A non-standard & obsolete version of $(( expression )) [1]
[1] http://wiki.bash-hackers.org/scripting/obsolete
花括号
${variable} Parameter substitution
${!variable} Indirect variable reference
{ command1; command2; . . . commandN; } Block of code
{string1,string2,string3,...} Brace expansion
{a..z} Extended brace expansion
{} Text replacement, after find and xargs
括号
( command1; command2 ) Command group executed within a subshell
Array=(element1 element2 element3) Array initialization
result=$(COMMAND) Command substitution, new style
>(COMMAND) Process substitution
<(COMMAND) Process substitution
双括号
(( var = 78 )) Integer arithmetic
var=$(( 20 + 5 )) Integer arithmetic, with variable assignment
(( var++ )) C-style variable increment
(( var-- )) C-style variable decrement
(( var0 = var1<98?9:21 )) C-style ternary operation
Truncate the contents of a variable
$ var="abcde"; echo ${var%d*}
abc
Make substitutions similar to sed
$ var="abcde"; echo ${var/de/12}
abc12
Use a default value
$ default="hello"; unset var; echo ${var:-$default}
hello
函数定义中的括号
括号()在函数定义中被使用:
function_name () { command1 ; command2 ; }
这就是在命令形参中也必须转义括号的原因:
$ echo (
bash: syntax error near unexpected token `newline'
$ echo \(
(
$ echo () { command echo The command echo was redefined. ; }
$ echo anything
The command echo was redefined.