Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what the differences between $var and ${var}

Tags:

shell

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

like image 201
mike Avatar asked Apr 19 '11 05:04

mike


People also ask

What is the difference between $VAR and $VAR in Shell?

2 Answers. There is no difference between echo $var and echo "$var" . However for other commands such as ls (list files) there could be a big difference. The double quotes " tells Linux to treat everything in between as a single entity.

What is ${ var in bash?

10.3.2. Using the ${#VAR} syntax will calculate the number of characters in a variable. If VAR is "*" or "@", this value is substituted with the number of positional parameters or number of elements in an array in general.

What is the difference between $* and $@?

$* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).


2 Answers

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.

like image 97
SiegeX Avatar answered Sep 30 '22 18:09

SiegeX


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

like image 34
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 19:09

Ignacio Vazquez-Abrams