简体   繁体   English

shell脚本传递带空格的参数

[英]shell script pass argument with space

I have the following script (example): 我有以下脚本(示例):

#!/bin/bash
while getopts a: opt; do
    case "$opt" in
        a) val="$OPTARG";;
        ?) echo "use the flag \"-a\""
           exit 2;;
    esac
done
echo "a specified with: ${val}"  

When I now call this script with test.sh -a "here is a string" the output is: a specified with: here but not as I would like to have a specified with: here is a string . 当我现在用test.sh -a "here is a string"调用这个脚本时, test.sh -a "here is a string"输出是: a specified with: here不是因为我想要a specified with: here is a string

I know that I can call the script with test.sh -a here\\ is\\ a\\ string or test.sh -a "here\\ is\\ a\\ string" and it will work. 我知道我可以用test.sh -a here\\ is\\ a\\ string来调用脚本test.sh -a here\\ is\\ a\\ stringtest.sh -a "here\\ is\\ a\\ string"它会起作用。 But in my case I can not manipulate the string I want to pass. 但在我的情况下,我无法操纵我想传递的字符串。
So how can I change my getopts function to make it work? 那么如何更改我的getopts函数以使其工作?

I also tried getopt , but I worked even more wors: 我也试过getopt ,但我的工作更加恶劣:

commandsShort="a:"
commandsLong="aval:"
TEMP=`getopt \
        -o $commandsShort \
        -l $commandsLong \
        -q \
        -n "$0" -- "$@"`

What am I doing wrong? 我究竟做错了什么?

This got solved in comments on your question. 这在你的问题评论中得到了解决。 :-) :-)

You're calling the script with: 你用以下方法调用脚本:

eval "test.sh $@"

The effect of this "eval" line, if "here is a string" is your option, is to create the command line that is in the quotes: 如果“这是一个字符串”是你的选择,这个“eval”行的效果是创建引号中的命令行:

test.sh here is a string

and eval uate it. eval审视你们了。

Per the additional comments, if you can avoid eval, you should. 根据附加注释,如果你可以避免eval,你应该。

That said, if you need it, you could always quote the string within the eval: 也就是说,如果你需要它,你总是可以在eval中引用字符串:

eval "test.sh \"$@\""

Or if you don't like escaping quotes, use singles, since your $@ will be expanded due to the outer quotes being double: 或者如果你不喜欢转义引号,请使用单曲,因为你的$@会因外引号加倍而扩展:

eval "test.sh '$@'"

And finally, as you mentioned in comments, just running directly may be the best option: 最后,正如您在评论中提到的,直接运行可能是最佳选择:

test.sh "$@"

Note that if your $@ includes the -a option, you may have a new problem. 请注意 ,如果$@包含-a选项,则可能会出现新问题。 Consider the command line: 考虑命令行:

test.sh "-a here is a string"

In this case, your entire string, starting with -a , is found in $1 , and you will have no options for getopts and no OPTARG. 在这种情况下,您的整个字符串(以-a开头)在$1找到,并且您将没有getopts和OPTARG的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM