Home > Net >  How to use double quotes when assigning variables?
How to use double quotes when assigning variables?

Time:10-02

There's a bash file with something like this:

FOO=${BAR:-"/some/path/with/$VAR/in/it"}

Are those double quotes necessary? Based on the following test, I'd say no, and that no quote at all is needed in the above assignment. In fact, it's the user of that variable that needs to expand it within double quotes to avoid wrong splitting.

touch 'some file'  # create a file
VAR='some file'    # create a variable for that file name
FOO=${BAR:-$VAR}   # use it with the syntax above, but no quotes
ls -l "$FOO"       # the file does exist (here we do need double quotes)
ls -l $FOO         # without quotes it fails searching for files `some` and `file`
rm 'some file'     # remove temporary file

Am I correct? Or there's something more?

CodePudding user response:

How to use double quotes when assigning variables?

Use them around the stuff to be assigned on the right side of =.

Are those double quotes necessary?

Not in this case, no.

Am I correct?

Yes. And it's always the user of the variable that has to quote it - field splitting is run when expanding the variable, so when using it it has to be quoted.

There are exceptions, like case $var in and var=$var - contexts which do not run field splitting, so like do not require quoting.

Or there's something more?

From POSIX shell:

2.6.2 Parameter Expansion

In addition, a parameter expansion can be modified by using one of the following formats. In each case that a value of word is needed (based on the state of parameter, as described below), word shall be subjected to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

${parameter:-word}

Because field splitting expansion is not run over word inside ${parameter:-word}, indeed, quoting doesn't do much.

  • Related