Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I see a lot of ${VARIABLE} type syntax in scripts. What is the point of the braces?

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

It delimits the variable.

You might need $FOO as a variable, but need to concat it with other text. If so, this won't work:

echo "$FOObar"

This will complain that there's no variable $FOObar. To get around this, delimit the variable:

echo "${FOO}bar"

This will work, and print the value of $FOO with the text 'bar' concatenated.

It's one of those things that people often choose to do all the time, to avoid problems where it's really required. It might be a good habit to get into, as bash scripting is very unforgiving of syntax mistakes.

share|improve this answer
add comment

@mauvedeity is correct. The issue isn't just that some characters, when written after a variable reference are considered part of that reference — it's also that some characters are then considered to not be part of it. This breaks for example variable manipulating operations and use of arrays.

Arrays:

$ foo=( one two three )
$ echo $foo # implied first element with index 0
one
$ echo $foo[1] # this will not work, as [1] is not considered part of variable
one[1]
$ echo ${foo[1]} # this will work
two
$ echo ${foo[*]} # all elements
one two three
$ echo ${#foo[*]} # array length
3
$ echo ${#foo[2]} # length of third element (index 2)
5

Variable operations

$ file=filename.txt
$ echo $file
filename.txt
$ echo ${file%.txt} # remove last match of .txt in $file
filename

All of this would fail (as illustrated in the array example) if we didn't explicitly set the delimiters for the variable reference.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.