The problem is that you used the wrong type of quotes. Shells interpolate variables inside double quotes, so the variable references were interpolated by the shell in which you ran sh -c "…"
. Assuming that this shell didn't have variables named arr
or var
defined, the argument to sh -c
was
arr=(1 2 3 4 5);for var in ;do echo ;done
If sh
is a shell that supports arrays, this is perfectly valid code, that happens to do nothing.
To pass a literal string to a command, use single quotes. All characters inside single quotes are interpreted literally, so you can use every character except a single quote in the string. (If you need a single quote, escape it as the four-character sequence '\''
.)
sh -c 'arr=(1 2 3 4 5);for var in ${arr[@]};do echo $var;done'
Beware that not all implementations of sh
support arrays. If you need arrays, you should explicitly invoke a shell that supports them.
ksh -c 'arr=(1 2 3 4 5);for var in ${arr[@]};do echo $var;done'
or
bash -c 'arr=(1 2 3 4 5);for var in ${arr[@]};do echo $var;done'
printf
will iterate if you provide more values than placeholders. Yourfor
loop can be written like this:bash -c 'arr=(1 2 3 4 5); printf "%s\n" "${arr[@]}"'
– glenn jackman Sep 10 '15 at 13:29