mike
mike

Reputation: 1137

what the differences between $var and ${var}

i see some code like this

  SERIAL_NO="121"
  if [ -z "${SERIAL_NO}" ]; then
     echo -e "ERROR: serial number of the device is not provided!"
     exit 1
  else

here it use ${SERIAL_NO} to got the SERIAL_NO variable. i want know what the difference between $var and ${var} and why use ${var} here.

thanks

Upvotes: 5

Views: 859

Answers (3)

SiegeX
SiegeX

Reputation: 140497

There actually is a minor difference performance wise. The reason there is a performance difference is because the braces enable the Parameter Expansion (PE) parser. Without the braces the shell knows that no parameter expansion will be performed (as the braces are mandatory for PE). The only reason to use the braces around a variable name when you don't want to perform a PE is to disambiguate the variable name from other text such as var="foo"; echo ${var}name will output fooname. Without the braces the shell will try to expand the variable named $varname which doesn't exist.

Upvotes: 5

seand
seand

Reputation: 5296

The braces are often used to prevent shell expansion and allow back-to-back variables. However in this case it may not be strictly needed.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799410

There is no difference, if no alphanumeric characters follow. The braces in your example are unneeded.

"$foo42" is the contents of $foo42. "${foo}42" is the contents of $foo followed by "42".

Upvotes: 1

Related Questions