[英]shell script pass argument with space
我有以下脚本(示例):
#!/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}"
当我现在用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
。
我知道我可以用test.sh -a here\\ is\\ a\\ string
来调用脚本test.sh -a here\\ is\\ a\\ string
或test.sh -a "here\\ is\\ a\\ string"
它会起作用。 但在我的情况下,我无法操纵我想传递的字符串。
那么如何更改我的getopts
函数以使其工作?
我也试过getopt
,但我的工作更加恶劣:
commandsShort="a:"
commandsLong="aval:"
TEMP=`getopt \
-o $commandsShort \
-l $commandsLong \
-q \
-n "$0" -- "$@"`
我究竟做错了什么?
这在你的问题评论中得到了解决。 :-)
你用以下方法调用脚本:
eval "test.sh $@"
如果“这是一个字符串”是你的选择,这个“eval”行的效果是创建引号中的命令行:
test.sh here is a string
和eval审视你们了。
根据附加注释,如果你可以避免eval,你应该。
也就是说,如果你需要它,你总是可以在eval中引用字符串:
eval "test.sh \"$@\""
或者如果你不喜欢转义引号,请使用单曲,因为你的$@
会因外引号加倍而扩展:
eval "test.sh '$@'"
最后,正如您在评论中提到的,直接运行可能是最佳选择:
test.sh "$@"
请注意 ,如果$@
包含-a
选项,则可能会出现新问题。 考虑命令行:
test.sh "-a here is a string"
在这种情况下,您的整个字符串(以-a
开头)在$1
找到,并且您将没有getopts和OPTARG的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.