What does ${x} mean?

Login or Register to Reply

Thread Tools Search this Thread
# 1  
Old 2 Weeks Ago
What does ${x} mean?

In POSIX shell, what is the difference between $x and ${x} ?



echo $x
echo ${x}

exit 0

They both print "1".
# 2  
Old 2 Weeks Ago
man sh:

The simplest form for parameter expansion is:


The value, if any, of parameter is substituted.

The parameter name or symbol can be enclosed in braces, which are optional except for positional parameters with more than one digit or when parameter is followed by a
character that could be interpreted as part of the name.
These 2 Users Gave Thanks to RudiC For This Post:
dodona (2 Weeks Ago) johnprogrammer (2 Weeks Ago)
# 3  
Old 2 Weeks Ago
The { and } are very useful for clarity. It is also very useful for these cases too:-
  • You want to refer to command line parameter ten or over. Some OSes would interpret $10 as actually the first parameter suffixed with a zero. You would need to refer to ${10} instead.
  • You might want to refer to a variable and put in a suffix of your own, then $var_suffix will not work, but ${var}_suffix will. The _suffix will be treated as though it is part of the variable name with the first format, but is just literal text appended after the value of the variable in the latter.

The second case might be a bit obscure, so perhaps a demonstration on the command line is better:-
$ a=Hello
$ a_b=world
$ echo $a
$ echo $a_b
$ echo ${a}_b

I hope that this helps and that I haven't confused things.

Last edited by rbatte1; 2 Weeks Ago at 05:41 AM.. Reason: Corrected my example. Oh how wrong I was trying to illustrate the issue but getting it backwards!
These 3 Users Gave Thanks to rbatte1 For This Post:
johnprogrammer (2 Weeks Ago) Neo (2 Weeks Ago) wisecracker (2 Weeks Ago)
Login or Register to Reply

Thread Tools Search this Thread
Search this Thread:
Advanced Search