5

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

mike
  • 1,127
  • 4
  • 17
  • 34
  • Does this answer your question? [What is the difference between ${var}, "$var", and "${var}" in the Bash shell?](https://stackoverflow.com/questions/18135451/what-is-the-difference-between-var-var-and-var-in-the-bash-shell) – Pound Hash Sep 23 '22 at 04:25

3 Answers3

5

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.

SiegeX
  • 135,741
  • 24
  • 144
  • 154
1

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".

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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.

seand
  • 5,168
  • 1
  • 24
  • 37