jeudi 2 février 2017

Correctly enclosing Bash variables with quotes

First of all, this is not related to using quotes inside a Bash variable (found a lot of forum posts about that looking for my answer). Anyway ...

I'm currently programming some of Bash scripts at work and have quite a lot of variables as well as many if statements. My question is if enclosing Bash variables with quotes can have some (maybe negative) side-effects and if there best-practice way for doing this.

So, let's say, I have that variable:

foo="bar"

I can check it as follows:

if [ $foo = "bar" ]; then (...)

if [ "$foo" = "bar" ]; then (...)

if [ $foo = bar ]; then (...) # doesn't work in case of multiple words inside $foo, of course

Is there anything against the following way?

if [ "$foo" = "bar" ]; then

Because, in this case if $foo was not defined, "" (empty string) would be compared with "bar". Without the quotes around $foo, there will be a syntax error. Correct me if I'm wrong.

So, can I use the above way in any compare case (I also want to have a consistent way to avoid a syntactic mess-up)?

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire