我们什么时候需要在 shell 变量周围使用花括号? [英] When do we need curly braces around shell variables?

查看:29
本文介绍了我们什么时候需要在 shell 变量周围使用花括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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

是否有显着差异,或者只是风格?一个比另一个更受欢迎吗?

Is there a significant difference, or is it just style? Is one preferred over the other?

推荐答案

在这个特定的例子中,它没有区别.但是,${} 中的 {} 如果您想扩展字符串中的变量 foo

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 标识的变量.

since "$foobar" would instead expand the variable identified by foobar.

在以下情况下也无条件需要大括号:

Curly braces are also unconditionally required when:

  • 扩展数组元素,如${array[42]}
  • 使用参数扩展操作,如${filename%.*}(删除扩展名)
  • 将位置参数扩展到 9 以上:"$8 $9 ${10} ${11}"
  • expanding array elements, 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.

这篇关于我们什么时候需要在 shell 变量周围使用花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆