在shell脚本中传递包含空格的参数

Jef*_*y04 29 shell

我需要我的脚本能够接受带有空格字符的参数.例如,如果我有一个如下脚本:

for SOME_VAR in $@
do
    echo "$SOME_VAR"
    cd "$SOME_VAR"
done;
Run Code Online (Sandbox Code Playgroud)

如果我将参数传递给脚本(假设它被调用foo.sh)

sh foo.sh "Hello world"
Run Code Online (Sandbox Code Playgroud)

我期待脚本打印Hello world并将目录更改为Hello world.但我收到此错误消息:

hello
cd: 5: can't cd to hello
world
cd: 5: can't cd to world
Run Code Online (Sandbox Code Playgroud)

我究竟如何将带有空格字符的参数传递给shell脚本中的命令?

Aar*_*lla 46

你也必须用$@引号括起来:"$@"

这告诉shell忽略参数中的空格; 它不会将所有参数都转换为非常长的字符串.

  • @AndreasWederbrand:不."$ @"是一个特殊的标记,意思是"用引号包装每个单独的参数".所以`a"b c"`变成(或者说保持)`"a""b c"`而不是"ab c"`或"a""b""c"`. (4认同)