What are the differences between the following variables in regards to scripting with BASH:
$var
"$var"
${var}
"${var}"
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.
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'
${var} form, unless you think that it will hurt readability.