In shell scripting, $var and ${var} are both used for variable expansion, but they have some subtle differences:
Difference 1: Word Splitting
When using $var, the shell may perform word splitting on the expanded value, which can lead to unexpected behavior.
var=”hello world”
echo $var – Output: hello world (word splitting occurs)
In contrast, ${var} prevents word splitting:
var=”hello world”
echo “${var}” – Output: hello world (no word splitting)
Difference 2: Pathname Expansion
Similarly, when using $var, the shell may perform pathname expansion (globbing) on the expanded value.
var=”.txt”
echo $var – Output: list of .txt files in the current directory (pathname expansion occurs)
Again, ${var} prevents pathname expansion:
var=”.txt”
echo “${var}” – Output: .txt (no pathname expansion)
Difference 3: Parameter Expansion
${var} allows for parameter expansion, which enables you to perform operations like substring removal, case modification, and more.
var=”hello”
echo “${var^^}” – Output: HELLO (parameter expansion: uppercase conversion)
In summary:
– Use $var when you want the shell to perform word splitting and pathname expansion on the expanded value.
– Use ${var} when you want to prevent word splitting and pathname expansion, or when you need to perform parameter expansion.
Best practice: Use ${var} consistently to avoid unexpected behavior and make your code more predictable and maintainable.