Why does bash variable expansion retain quotes?

> echo "hi"
hi
> VAR='echo "hi"'
> $VAR
"hi"

Why is the output of the above commands different?

A similar thing occurs with single quotes:

> VAR="echo 'hi'"
> $VAR
> 'hi'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The extra pair of quotes would be consumed only by an extra evaluation step. For example forced by eval:

bash-4.2$ VAR='echo "hi"'

bash-4.2$ $VAR
"hi"

bash-4.2$ eval $VAR
hi

But generally is a bad idea to put commands with parameters in one string. Use an array instead:

bash-4.2$ VAR=(echo "hi")

bash-4.2$ "${VAR[@]}"
hi

Method 2

Quote removal only occurs on the original input words, not on the result of expansions. Quotes that are part of expanded variables are untouched.

Method 3

If you step back a bit, you can see why variable substitution absolutely should retain quotes.

The point of quotes in a Unix/Linux/BSD shell is to keep pieces of a string together that would otherwise get parsed as multiple strings. Since by default a shell uses whitespace as a token separator, a string with spaces (like “one two three”) if not quoted or escaped somehow, would get parsed as 3 strings: “one”, “two” and “three”.

If a programmer wants a string with the value of some variable interpolated:

VAR=two
STRING="one $VAR three"

the shell should absolutely not remove the quotes: the string containing spaces would get parsed as 3 smaller strings.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x