Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to quote command substitutions during variable assignment in bash?

Tags:

bash

shell

sh

Nearly everywhere I've read, including Google's bash scripting style guide mention to necessity of quoting command substitutions (except when specifically desired of course).

I understand the when/where/why of quoting command substitutions during general use. For example: echo "$(cat <<< "* useless string *")" rather than echo $(...)

However for variable assignments specifically, I have seen so many examples as such: variable="$(command)"

Yet I have found no instances where variable=$(command) is not equivalent.

variable="$(echo "*")" and variable=$(echo "*") both set the value to '*'.

Can anyone give any situations where leaving the substitution unquoted during variable assigment would actually cause a problem?

like image 851
Six Avatar asked Nov 24 '14 09:11

Six


People also ask

What does bash do when it performs command substitution?

Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

When performing command substitution do you use double quotes?

There are a few other contexts where the double quotes are optional, but you can't go wrong with the simple rule: always use double quotes around variable and command substitutions unless you want the split+glob operator.

Does bash echo need quotes?

Echoing textThe echo command doesn't require any variety of quote characters much of the time. You can echo a phrase like this without bothering with quotes of any kind.

What does command substitution allow?

Command substitution allows you to capture the output of any command as an argument to another command. You can perform command substitution on any command that writes to standard output. The read special command assigns any excess words to the last variable.


1 Answers

The shell does not perform word splitting for variable assignments (it is standardized that way by POSIX and you can rely on it). Thus you do not need double quotes (but you can use them without making the result different) in

variable=$(command)   # same as variable="$(command)"

However, word-splitting is performed before executing commands, so in

echo $(command)
echo "$(command)"

the result may be different. The latter keeps all multi-space sequences, while the former makes each word a different argument to echo. It is up to you to decide which is the desired behavior.

Interesting shell quirk: there is one more place where quoting a substitution or not makes no difference, namely the expression in a case expr in construct.

case $FOO in
  (frob) ...;;
esac

is indistinguishable from

case "$FOO" in
  (frob) ...;;
esac
like image 195
Jens Avatar answered Oct 13 '22 16:10

Jens