Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

unix - What's the difference between ${varname} and $varname in a shell scripts

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Quoting from info bash:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...