什么时候需要在外壳变量周围加上花括号? [英] When do we need curly braces around shell variables?

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

问题描述

在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.

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

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