1

So apparently arrays in bash have specials rules for what might be the first element, any explanation for this?

jgo ~$ myarray=(-n foo) && echo ${myarray[@]}
foo
jgo ~$ myarray=(-v foo) && echo ${myarray[@]}
-v foo
jgo ~$ myarray=(-a foo) && echo ${myarray[@]}
-a foo
jgo ~$ myarray=(-e foo) && echo ${myarray[@]}
foo
0

1 Answer 1

4

Actually, your output should look more like this:

jgo ~$ myarray=(-n foo) && echo ${myarray[@]}
foojgo ~$ myarray=(-v foo) && echo ${myarray[@]}
-v foo
jgo ~$ myarray=(-a foo) && echo ${myarray[@]}
-a foo
jgo ~$ myarray=(-e foo) && echo ${myarray[@]}
foo

The reason is that -n and -e are valid options to echo whereas the other ones you tried aren't.

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

4 Comments

That's correct. I noticed when I tried it on a proper linux box, the output in the question is from cygwin.
good one. So if you use printf instead of echo, the output is fine. Also if you quote the elements in the array.
Or just add space before $myarray --> ` myarray=(-n foo) && echo " ${myarray[@]}"` if you still want to use echo
@Samuel Or as there is no reason to expand the array elements separately you could use echo "${myarray[*]}" which keeps it all as a single arg to echo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.