mora
mora

Reputation: 2287

Why does quote in quoted variable expansion works well in bash?

I am learning quote in bash. I got a code

unset unset_var
test_var="${unset_var:-"abc"}"
echo "test_var = $test_var"
tset_var = abc

My question comes from the line, "${unset_var:-"abc"}"

I interupted the line in two ways,

The first ways is

"${unset_var:-"abc"}" =
(quoted string: "${unset_var:-") +
(unquoted string: abc) +
(quoted string: "}")

The second way is

"${unset_var:-"abc"}" =
("${}") + (abc:-"abc")

The first way is intuitive for me.

The second way is similar to independent quote in sub-shell from parent-shell, like

"$(command "aug")"  # quote in sub-shell is independent from one in parent-shell

I could not find a instruction of this question in bash manual.

Someone who knows how it works, please let me know. Thank you.

Upvotes: 1

Views: 62

Answers (1)

chepner
chepner

Reputation: 531255

In any assignment statement of the form

name=value

value undergoes quote-removal, which is the removal of any quotes that are not a result of expansions applied to value.

With

test_var="${unset_var:-"abc"}"

the quotes around the parameter expansion are clearly not the result of any expansions, so they are removed. The question is, how are the inner quotes treated?

According to the man page,

In [${parameter:-word}], word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion."

However, since "abc" does not undergo any of the four named expansions, the surrounding quotes are not the product of an expansion, and so are removed per quote removal. Thus,

test_var="${unset_var:-"abc"}"

is equivalent to

test_var="${unset_var:-abc}"

which is equivalent to

test_var=abc

Upvotes: 2

Related Questions