getopts 截断参数值
我需要在 myscript.sh 中传递一个包含 spaced 作为选项的字符串值 代码如下所示:
while getopts "m:i:t:" OPTION
do
case $OPTION in
m)
M=$OPTARG
echo M: $M
;;
i)
I=$OPTARG
echo I: $I
;;
t)
T=$OPTARG
echo T: $T
;;
?)
usage
exit
;;
esac
done
当我直接在命令行上调用它时,它工作得很好:
./myscript.sh -m 1 -i '0 1 2 3' -t '2142'
M: 1
I: 0 1 2 3
T: 2142
但是,我需要将 -i 作为字符串变量传递,但我无法让它工作。选项 -i 的字符串被截断,选项 -t 甚至没有出现(可能是新行)。
I='0 1 2 3'
./myscript.sh -m 1 -i "'"$I"'" -t '2142'
M: 1
I: '0
I='0 1 2 3'
II="'"$(echo $I)"'"
./myscript.sh -m 1 -i $II -t '2142'
M: 1
I: '0
有什么建议吗?谢谢!
I need to pass a string value containing spaced as option in myscript.sh
The code looks like this:
while getopts "m:i:t:" OPTION
do
case $OPTION in
m)
M=$OPTARG
echo M: $M
;;
i)
I=$OPTARG
echo I: $I
;;
t)
T=$OPTARG
echo T: $T
;;
?)
usage
exit
;;
esac
done
It works just fine when I call it directly on the command line:
./myscript.sh -m 1 -i '0 1 2 3' -t '2142'
M: 1
I: 0 1 2 3
T: 2142
However, I need to pass the -i as a string variable and I cannot get it to work. The string for option -i gets truncated and option -t does not even come through (possibly a new line).
I='0 1 2 3'
./myscript.sh -m 1 -i "'"$I"'" -t '2142'
M: 1
I: '0
I='0 1 2 3'
II="'"$(echo $I)"'"
./myscript.sh -m 1 -i $II -t '2142'
M: 1
I: '0
Any suggestions? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你尝试运行它时,为什么要这样引用?我很确定这就是您想要做的:
双引号将其中的所有字符视为文字,除了一些内容,包括
$
,它允许扩展变量。单引号也停止变量扩展。它们各自保护另一种类型的引号,因此"'"
只是一个'
字符,而'"'
只是一个"
字符。这意味着
"'"$I"'"
变成'0 1 2 3'
,单引号没有特殊含义,并且对空格没有保护 -您也可以将其写为\'0 1 2 3\'
。由于空格不受保护,因此将单词分开,因此第一个单词是\'0
。因此,您的脚本将其视为选项的值,并将1
、2
和3'
作为额外参数。如果在 while 循环之后添加shift $((OPTIND - 1))
移走已解析的选项,然后echo "arguments: $@"
在你的选项解析之后。您还会看到,由于getops
期望所有选项都放在前面,这导致您错过了-t
选项,也将其视为参数。Why are you quoting like that when you try to run it? This I'm pretty sure this is what you meant to do:
Double quotes treats all characters inside them as literal, except a few things, including
$
, which allows variables to be expanded. Single quotes stop variable expansion as well. They each protect the other type of quote, so that"'"
is just a'
character, and'"'
is just a"
character.This means that
"'"$I"'"
turns into'0 1 2 3'
, with no special meaning for the single quotes, and no protection for the spaces - you might also write it as\'0 1 2 3\'
. The spaces, being unprotected, split up words, so the first word is\'0
. Your script therefore sees that as the value for the option, and1
,2
, and3'
as extra arguments. You can see this if after your while loop you addshift $((OPTIND - 1))
to shift away the parsed options, and thenecho "arguments: $@"
after your option parsing. You'll also see that sincegetops
expects all the options together at the front, this has caused you to miss out on the-t
option, treating it as an argument too.