Do I need to specify command substitution when assigning variables in bash?

Almost everywhere I read, including the bash style guide, Google bash mentions the need to quote command substitutions (unless it was especially desirable).

I understand when / where / why command quotes are replaced during general use. For example: echo "$(cat <<< "* useless string *")" and not echo $(...)

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

But I did not find instances where variable=$(command) not equivalent.

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

Can someone give any situations where leaving a replacement without quotes while choosing a variable will really cause a problem?

+6
source share
3 answers

The shell does not split words to assign variables (standardized in this way with POSIX, and you can rely on it). This way you don't need double quotes (but you can use them without making the result different) in

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

However, before executing the commands, word splitting is performed, therefore, in

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

The result may be different. The latter preserves all multidimensional sequences, while the former makes each word a different argument for echo. It is up to you to decide which one is needed.

An interesting quirk shell: there is another place where quoting a substitution or does not make any difference, namely the expression in the case expr in construct.

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

indistinguishable from

 case "$FOO" in (frob) ...;; esac 
+6
source

When using BASH, these two lines are 100% equivalent:

 variable="$(command)" variable=$(command) 

while the two are not:

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

Alas, the human brain is not a computer. This is especially not so reliable when it comes to repetition of work.

So, if you mix styles (i.e. you indicate when you use the arguments of the command, but do not indicate when assigning a variable), you will be mistaken from time to time.

Worse, from time to time you will need the result of the team to be expanded into separate words. And the next guy who reads your code wonders if he is looking at the error.

Competition: since the first two lines are the same, itโ€™s easier in the middle brain to always indicate $() (even if itโ€™s not necessary) so that you always indicate when you need to.

+4
source

Testing with lots of commands is the same thing. Unable to find the difference.

-2
source

Source: https://habr.com/ru/post/978607/


All Articles