我们什么时候需要使用bash变量大括号? [英] When do we need curly braces in variables using Bash?
问题描述
在shell脚本中,当我们使用 {}
扩大变量的时候?
In shell scripts, when do we use {}
when expanding variables?
例如,我已经看到了以下内容:
For example, I have seen the following:
var=10 # Declare variable
echo "${var}" # One use of the variable
echo "$var" # Another use of the variable
是否有显著差异,还是仅仅是风格?一个preferred比其他?
Is there a significant difference, or is it just style? Is one preferred over the other?
推荐答案
在这个特殊的例子,它没有什么区别。但是, {}
在 $ {}
如果你想扩展该变量是有用的富字符串中的
In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
因为$ foobar的
将改为展开 foobar的
。
花括号也无条件需要时:
Curly braces are also unconditionally required when:
- 扩展阵列,如
$ {数组[42]}
- 使用参数扩展业务,如
$ {文件名%。*}
(删除扩展名) - 扩展位置参数超出9:
$ $ 8 9 $ {10} $ {11}
- expanding arrays, as in
${array[42]}
- using parameter expansion operations, as in
${filename%.*}
(remove extension) - expanding positional parameters beyond 9:
"$8 $9 ${10} ${11}"
随处可见这样做,而不是仅仅在潜在不确定的情况下,可以被认为是良好的编程习惯。这既有一致性,避免像 $ foo_ $ bar.jpg
,它看起来并不明显,下划线变成变量名的一部分。惊喜
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
这篇关于我们什么时候需要使用bash变量大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!