0

This is a theoretical question to understand what is going behind the scenes.

If I run this:

q=( 11 22 33 )
q="${q-()}"
declare -p q

it outputs the expected:

declare -a p=([0]="11" [1]="22" [2]="33")

But if I run:

q=( 11 22 33 )
q="${q[@]-()}"
declare -p q

then I get this:

declare -a p=([0]="11 22 33" [1]="22" [2]="33")

I understand which way is the correct one, but I cannot explain why the latter produces the result it does. Can someone explain this?

0

1 Answer 1

2

Assigning to q, when it already has its array attribute set, is equivalent to assigning to q[0]. That is, you would get the same result with

q[0]="${q[@]-()}"

In your first code, ${q-()} also expands to ${q[0]-()} for the same reason, and that value is assigned back to q[0], resulting in an apparent no-op. (In every case, ${...-()} is the same as ${...}, since you aren't dealing with any unset variables.)

Sign up to request clarification or add additional context in comments.

4 Comments

So, in the first case, I am assigning q[0] to q[0] right?
Exactly. I should add that to the answer.
Alright! So, this has the effect I thought it had, ie initialize q to an array if it is not set already, otherwise keep it the same (although just by setting q[0] to q[0]). If I wanted to use another array inside the curly brackets to assign to q, how should I have written the assignment?
To answer my comment, if you assign a new array directly to q then it gets set to the new array, eg q=(aa bb cc) or q=("{other_arr[@]}").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.