0

I write bash scripts about once every 5 years, so probably a noob question. This is on OSX.

Paired down script:

#!/bin/bash
array=(
  '<item name="Alice" title="President"/>'
  '<item name="Bob" title="CEO"/>'
)

for k in "${array[@]}"; do
  find=${array[$k]}
done

Here is the error: line 8: <item name="Alice" title="President"/>: syntax error: operand expected (error token is "<item name="Alice" title="President"/>")

Can't figure this one out. Thanks for any help.

1 Answer 1

1

The variable k in the for loop holds the element (value) of the array, not the index. So you need to say:

for k in "${!array[@]}"; do
    find="${array[$k]}"
done

or

for e in "${array[@]}"; do
    find="$e"
done
Sign up to request clarification or add additional context in comments.

4 Comments

The first suggestion did not work. Same error. However the second one did. Thanks very much!
@Cyrus thank you for the elaboration. As you know it is not necessary to double-quote the right-hand variable when assigning to another variable, I'd admit it is a good practice to quote anyway.
@tshiono: What if array element contains leading or trailing white spaces or consecutive white spaces or a single *?
@Cyrus the mentioned whitespaces are preserved. But a single * will make a definitive difference. Understood.

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.