I know that ${var}
and $var
does the same thing. I also know that you can use brace for advanced options like ${var:=word}
or ${var#pattern}
. It's also explained here.
But I see in some bash scripts the use of braces in the simplest form : ${var}
and sometimes I see only this notation $var
.
Is there any reason to prefer this syntax over the simple $var
as it does the same thing ? Is it for portability ? Is it a coding style ?
As a conscientious developer, which syntax I should use ?
{...}
or not is a cosmetic matter (I personally find it clutters scripts when not necessary), and when they are needed and you forget them, that's an error you would detect at authoring time. In comparison, forgetting quotes around variables is a mistake and an error you don't always detect at authoring time, but your users at run time. I find it exasperating when people go all the trouble of adding those{}
when they are not necessary but forget to quote. IOW,rm ${file}
is wrong, whether to userm -- "$file"
orrm -- "${file}"
is a cosmetic choice. – Stéphane Chazelas Jun 09 '16 at 11:33${11}
(though it's not needed in all shells (not in zsh, csh, tcsh)). Also note that${foo}_bar
can also be written"$foo"_bar
or$foo''_bar
or$foo\_bar
(I'd still prefer"${foo}_bar"
). – Stéphane Chazelas Jun 09 '16 at 11:35csh
,tcsh
orzsh
you also need it before a:
to prevent history modifiers (${var}:h
as otherwise$var:h
would mean the head of$var
). – Stéphane Chazelas Jun 09 '16 at 11:38bash
. As you say, there are various methods of indicating the end of the variable name, but I prefer curly braces. I find them more clear and more consistent than the alternatives, since they are used for various types of complex parameter expansions, including arrays. – Michael Vehrs Jun 09 '16 at 11:45$foo_bar
instead of"$foo"_bar
, so I think I will still use the simplest form$foo
. Obviously, quoting variables is the most important, and it's really clear in my mind. – Nairolf21 Jun 09 '16 at 18:05