我们何时需要围绕shell变量使用花括号?
  在shell脚本中,我们何时在扩展变量时使用{} ? 
例如,我看到以下内容:
var=10        # Declare variable
echo "${var}" # One use of the variable
echo "$var"   # Another use of the variable
是否有重大差异,还是只是风格? 一个比另一个更受欢迎吗?
  在这个特定的例子中,它没有区别。  然而, {}在${}如果你想扩展变量是有用的foo字符串中 
"${foo}bar"
  因为"$foobar"会改为扩展foobar 。 
在下列情况下,花括号也是无条件要求的:
${array[42]} ${filename%.*} (移除扩展名) "$8 $9 ${10} ${11}"   在任何地方这样做,而不仅仅是在潜在模糊的情况下,可以被认为是良好的编程实践。  这既是为了一致性,也是为了避免像$foo_$bar.jpg这样的$foo_$bar.jpg ,其中下划线变成变量名的一部分在视觉上不明显。 
  变量声明和分配时不需要$和{} 。  你必须使用 
var=10
  分派。  为了读取变量(换句话说,'展开'变量),您必须使用$ 。 
$var      # use the variable
${var}    # same as above
${var}bar # expand var, and append "bar" too
$varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.
  这有时让我感到困惑 - 在其他语言中,我们以相同的方式引用变量,而不管它是在作业的左侧还是右侧。  但是shell脚本是不同的, $var=10不会做你认为它会做的事! 
  您可以使用{}进行分组。  大括号需要取消引用数组元素。  例: 
dir=(*)           # store the contents of the directory into an array
echo "${dir[0]}"  # get the first entry.
echo "$dir[0]"    # incorrect
上一篇: When do we need curly braces around shell variables?
下一篇: How can I replace every occurrence of a String in a file with PowerShell?
