Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variable formats

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

$var
"$var"
${var}
"${var}"
like image 929
E1Suave Avatar asked Apr 23 '26 11:04

E1Suave


1 Answers

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.

like image 101
sorpigal Avatar answered Apr 25 '26 02:04

sorpigal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!