Shell脚本中大括号{}和方括号()之间的区别 [英] Difference between braces {} and brackets () in shell scripting
问题描述
我们使用大括号 {}
来表示变量,例如
We use braces {}
for variable expression like
NAME="test"
FILE_NAME=${NAME}file
但是我不明白在哪种情况下我们使用方括号()
说 nslookup $(hostname)
仅适用于()
方括号。
But I don't understand in which scenarios we use brackets ()
Say nslookup $(hostname)
works only with ()
brackets.
有人可以解释吗?
推荐答案
未成年人首先是nitpick:
Minor nitpick first:
- 托架
[]
- 括号
()
- 括号
{}
- (双精度)引号
- (单)引号(撇号)
''
- 反引号
``
(与波浪号〜键相同)
- Brackets
[]
- Parentheses
()
- Braces
{}
- (Double) Quotation marks
""
- (Single) Quotation marks (apostrophes)
''
- Backticks
``
(Same as the tilde ~ key)
括号在BASh脚本中用于复杂的变量扩展。考虑字符串串联:
Braces are used in BASh scripts for complex variable expansion. Consider string concatenation:
STR="hello"
STR2=$STR
STR2
的值为 hello。如果您想使其类似于 helloWorld,该怎么办。做类似 STR2 = $ STR2World
的操作是行不通的,因此您使用花括号,即: STR2 = $ {STR} World
。
STR2
evaluates to "hello". What if you wanted to make it something like "helloWorld". Doing something like STR2="$STR2World"
won't work, so you use braces, ie: STR2="${STR}World"
.
与方括号一样,它们与反引号`一样使用,后者将它们之间的文本扩展为命令的文本输出。
As for brackets, they are used, similar to the backtick, `, which expands the text between them as the text output from a command.
如果要将当前时间存储为字符串怎么办?
What if you wanted to store the current time as a string?
STR2=$(date)
现在 STR2
存储字符串 PDT 2015年5月7日星期四09:32:06。
Now STR2
stores the string "Thu May 7 09:32:06 PDT 2015".
此外,您可以使用括号在子Shell中执行某些操作,这可能会影响您的环境,PID等。非常有用对于需要跟踪/恢复环境变量的废弃环境的情况,可通过 pushd
/ popd
进行目录而不是 cd
等
Additionally, you can use parentheses to execute something in a subshell, which will potentially affect your environment, PID, etc. Very useful for cases where you want a "throwaway" environment with having to track/restore environment variables, directories via pushd
/popd
instead of cd
, etc.
这篇关于Shell脚本中大括号{}和方括号()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!