我需要我的脚本能够接受带有空格字符的参数.例如,如果我有一个如下脚本:
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忽略参数中的空格; 它不会将所有参数都转换为非常长的字符串.