在shell脚本中传递包含空格的参数 [英] Passing argument containing space in shell script

查看:125
本文介绍了在shell脚本中传递包含空格的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need my script to be able to accept arguments with space characters. If, for example, I have a script as follows:

for SOME_VAR in $@
do
    echo "$SOME_VAR"
    cd "$SOME_VAR"
done;

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

If I pass arguments to the script (assuming it is called foo.sh)

sh foo.sh "Hello world"

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

I am expecting the script to print Hello world and change the directory to Hello world. But I get this error message instead:

hello
cd: 5: can't cd to hello
world
cd: 5: can't cd to world

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

How exactly do I pass an argument with a space character to a command in a shell script?

推荐答案

您也必须将 $@ 括在引号中:"$@"

You must wrap the $@ in quotes, too: "$@"

这告诉 shell 忽略参数中的空格;它不会将所有参数都变成一个很长的字符串.

This tells the shell to ignore spaces in the arguments; it doesn't turn all arguments into a very long string.

这篇关于在shell脚本中传递包含空格的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆