Bash – Why Does Variable Expansion Retain Quotes?

bashquotingshell

> 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'

Best Answer

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
Related Question