3

What are the differences between the following variables in regards to scripting with BASH:

$var
"$var"
${var}
"${var}"

2 Answers 2

7

There is no difference between $var and ${var} and there is no difference between "$var" and "${var}", except that in certain cases the parser may not be able to identify your intent when you user the former versions. Consider:

foo=hello
echo "$fooworld"
echo "${foo}world"

The first echo prints nothing, because the variable fooworld is not defined. The second prints helloworld because the shell was able to determine that you were referencing the foo variable.

The difference between $var and "$var" is that unquoted variable expansions are evaluated by the shell after the expansion. As such:

var='ls /'
$var

Lists /, because after the expansion the shell evaluates the space as a token separator, whereas

var='ls /'
"$var"

Results in ls /: No such file or directory because no command named ls / is available in the user's environment.

Sign up to request clarification or add additional context in comments.

Comments

2

The ones in quotes are expanded to a single parameter and not chopped up into separate words.

The ${var} notation is useful if the next character could be part of the variable name, eg: "${var}name".

function args() {
  while [ $# -gt 0 ]; do echo "arg: '$1'"; shift; done
}

# var=" a b  c"

# args $var
arg: 'a'
arg: 'b'
arg: 'c'

# args "$var"
arg: ' a b  c'

5 Comments

Is it inappropriate to use the ${var} notation at all times? Would this or could this cause issues depending on if the variable was a command E.g. var=$(echo hi) or if the variable was a simple string E.g var="hi" ?
"variable was a command" - you mean the variable was set to contain the output of a command? no, there's no difference. it's just a variable
It is always appropriate to use the ${var} form, unless you think that it will hurt readability.
@KarolyHorvath I did actually mean "the output of a command", thank you for the help and clarification.
@Sorpigal Thanks for the help. I personally like the way ${var} looks while reading my scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.