sh -c not get the right output when execute shell script

pal*_*din 2 shell

I loop to get data from array in shell ,
It works when I execute it in a shell file, with this content:

arr=(1 2 3 4 5)  
for var in ${arr[@]};  
do  
    echo $var  
done
Run Code Online (Sandbox Code Playgroud)

But there isn't any output when I use sh -c like below:

sh -c "arr=(1 2 3 4 5);for var in ${arr[@]};do echo $var;done"
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 6

Your problem is using sh -c "...", see @Gilles's answer for more details.

Further more, sh (refer to POSIX sh) does not support array (strictly speaking, it has only one array, $@), you need to call other shells on your system, which support array like bash, zsh or ksh.

bash -c 'arr=(1 2 3 4 5);for var in "${arr[@]}";do echo "$var"; done'
Run Code Online (Sandbox Code Playgroud)

另请注意,在${arr[@]}取消引用时您有一个错误,实际上您需要for var in "${arr[@]}"改为。调用不带引号的变量调用 split+glob 并且是许多安全隐患的来源

要使用 POSIX sh,您可以使用$@

set -- 1 2 3 4 5
for var do
  printf '%s\n' "$var"
done
Run Code Online (Sandbox Code Playgroud)

  • @MateuszPacek:OP 调用 `sh -c` 内联脚本而不是创建 shell 脚本。在这种情况下,shebang 没有帮助。 (2认同)
  • @c4f4t0r 只有当你的 `sh` 不是真正的 `sh` 而实际上是伪装的 `bash`、`zsh` 或 `ksh` 时,这才有效。你不应该真正使用 `bash` 特性,而 shell 调用为 `sh`,因为有一天它可能会崩溃(考虑 Debian,使用 `sh` 一个符号链接到 `dash` 而不是 `bash`)。 (2认同)