如何在Bash中使用getopts允许非可选参数位于可选参数前面?
我知道如何在Bash中使用getopts处理可选参数如何在Bash中使用getopts允许非可选参数位于可选参数前面?,bash,getopts,Bash,Getopts,我知道如何在Bash中使用getopts处理可选参数 #!/bin/bash while getopts ":a:p:drh" opt; do case "$opt" in a) echo $OPTARG;; esac done 但是如果我的脚本需要/script.sh arg1[options],我如何告诉getopts跳过arg1 $ ./script.sh -a 1234 1234 $ ./script.sh arg1 -a 1234 $ ./script.sh arg
#!/bin/bash
while getopts ":a:p:drh" opt; do
case "$opt" in
a) echo $OPTARG;;
esac
done
但是如果我的脚本需要/script.sh arg1[options]
,我如何告诉getopts
跳过arg1
$ ./script.sh -a 1234
1234
$ ./script.sh arg1 -a 1234
$ ./script.sh arg1
$ ./script.sh -a 1234 arg1
1234
如我所见,如果论点放在最后一个位置,我可以处理论点。在getopts
中,我需要什么“regex”来允许我的位置参数位于可选参数前面
来自的建议似乎在重新排列参数。如果您知道位置参数的数量,则可以执行以下操作:
#!/bin/bash
VAR=$1
shift
echo $VAR
while getopts ":a:p:drh" opt; do
case "$opt" in
a) echo $OPTARG;;
esac
done
例如:
> ./test.sh mist -a 2345 -p 45
mist
2345
我会这样做的。您可以在任意位置放置多个非可选参数
#!/bin/bash
while [ $# -gt 0]; do
while getopts ":a:p:drh" opt; do
case "$opt" in
a) echo $OPTARG; shift;;
p) echo $OPTARG; shift;;
d) echo Option d;;
r) echo Option r;;
h) echo Option h;;
\?) echo unknown Option;;
:) echo missing required parameter for Option $OPT;;
esac
shift
OPTIND=1
done
if [ $# -gt 0 ]; then
POSITIONALPARAM=(${POSITIONALPARAM[@]} $1)
shift
OPTIND=1
fi
done
echo ${POSITIONALPARAM[@]}
内部循环解析参数。每当遇到非选项参数时,它将退出内部循环。外部循环将获取下一个非选项参数。移除非选项参数后,内环将拾取,然后继续读取下一个可选参数,依此类推
正如我所解释的,移位会删除第一个参数(可选或不可选),并将所有内容向左移动一个位置<代码>$1被删除,$2
变为$1
,$3
变为$2
,依此类推。这为脚本提供了移动非可选参数的控件,直到它变为$1
shift
和重置optin
都可以实现这一点。感谢您的建议,OPTIND应该重置为1而不是0
/sample.bash-一个一p两个多d样本
输出:
one
two
Option d
more sample
one
two
Option d
more sample
现在让我们用不同位置的参数调用脚本
/sample.bash more-a one-p two-d样本
输出:
one
two
Option d
more sample
one
two
Option d
more sample
OPTIND
应该是1,而不是0。注意移位
的位置可能也是一个好主意,因为它们对该方法至关重要。OPTIND可以是0或1,只要它不大于1。唯一的要求是重置OPTIND。但是,如果您确实知道在某些实现中,将OPTIND设置为0不起作用,那么我必须开始重置为1,而不是像我以前那样重置为0。谢谢你花时间告诉我。知识就是力量。“如果应用程序将OPTIND设置为值1,则可以使用一组新的参数……任何其他调用getopts的尝试……如果OPTIND值被修改为1以外的值,则会产生未指定的结果。”@Chrono Kitsune-I将其更新为将OPTIND
重置为1,而不是0。酷,@alvits。我给了他荣誉,因为他先回答了,这实际上更容易理解,但我确实从你的回答中学到了东西。谢谢向上投票!