本文介绍了shell 脚本中的 ${varname} 和 $varname 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,但我想知道 ${varname}$varname 之间有什么区别?

I have a simple question but I wonder what is the difference between ${varname} and $varname ?

我两者都用,但我看不出有什么区别可以告诉我何时使用其中一个.

I use both but I don't see any difference which could tell me when to use one or the other.

推荐答案

在变量名中使用 {} 有助于在执行变量扩展时消除歧义.

Using {} in variable names helps get rid of ambiguity while performing variable expansion.

考虑两个变量 varvarname.让我们看看您想将字符串 name 附加到变量 var.你不能说$varname,因为这会导致变量varname 的扩展.然而,说 ${var}name 会帮助你达到预期的结果.

Consider two variables var and varname. Lets see you wanted to append the string name to the variable var. You can't say $varname because that would result in the expansion of the variable varname. However, saying ${var}name would help you achieve the desired result.

$ var="This is var variable."
$ varname="This is varname variable."
$ echo $varname
This is varname variable.
$ echo ${var}name
This is var variable.name

访问数组的任何元素时也需要大括号.

Braces are also required when accessing any element of an array.

$ a=( foo bar baz )       # Declare an array
$ echo $a[0]              # Accessing first element -- INCORRECT
foo[0]
$ echo ${a[0]}            # Accessing first element -- CORRECT
foo

引用info bash:

   Any  element  of  an  array may be referenced using ${name[subscript]}.
   The braces are required to avoid conflicts with pathname expansion.

这篇关于shell 脚本中的 ${varname} 和 $varname 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 02:44