Abh*_*ran 7 shell-script getopts
我按照这里的教程学习如何使用getopts
. 我能够执行用户正确提供的所有选项。但是现在我想在没有提供任何选项时执行默认选项。
例如:
while getopts ":hr" opt; do
case $opt in
h )
show_help;
exit 1
;;
r )
echo "Default option executed"
;;
esac
done
Run Code Online (Sandbox Code Playgroud)
因此,如果用户提供-h
或-r
,则应执行相应的命令(实际上确实如此),但是当没有提供这些选项时-r
,默认情况下应执行。有没有办法实现这一目标?
更新
我尝试了cas's
建议并包含*)
在我的getopts
功能中,但似乎没有发生任何事情。
while getopts ":hr" opt; do
case $opt in
h )
show_help;
exit 1
;;
r )
echo "Default option executed"
;;
\? )
echo error "Invalid option: -$OPTARG" >&2
exit 1
;;
: )
echo error "Option -$OPTARG requires an argument."
exit 1
;;
* )
echo "Default option executed"
;;
esac
done
Run Code Online (Sandbox Code Playgroud)
这个片段有什么问题吗?
向语句添加默认选项case
不会有帮助,因为如果getopts
没有要解析的选项,则不会执行该语句。您可以看到它使用 shell 变量处理了多少个选项OPTIND
。从help getopts
:
Each time it is invoked, getopts will place the next option in the
shell variable $name, initializing name if it does not exist, and
the index of the next argument to be processed into the shell
variable OPTIND. OPTIND is initialized to 1 each time the shell or
a shell script is invoked.
Run Code Online (Sandbox Code Playgroud)
因此,如果OPTIND
为 1,则不处理任何选项。在循环后添加以下内容while
:
if (( $OPTIND == 1 )); then
echo "Default option"
fi
Run Code Online (Sandbox Code Playgroud)
据我所知, r 并不期待争论。从逻辑上讲,无论发生什么,r 都会以相同的方式执行。
我会将与 r 相关的命令从 getopts 子句中取出并让它执行。我相信这足以满足您的要求。换句话说,将 echo 语句放在“done”语句之后。
如果您希望出于兼容性或其他原因,可以将 r 作为存根保留在 getopts 中。
您还可以添加设置为零的变量作为开关。一旦选择了除 r 之外的任何选项,就会有一行将该变量更改为 1。在完成语句之后,您可以编写“如果变量等于 0,则执行默认命令”。
我想我最喜欢Cas的回答。我想发表评论,但我没有特权。我会以他的想法为基础。这与 Cas 提出的相同,但你只有一个命令(所以你不会有两个相同的命令并在将来犯错误),并且它会给你除了 - 之外还使用它的可能性H。
DEF="Default command executed"
while getopts ":hr" opt;
do case $opt in
h) show_help;
exit 1 ;;
r) echo "$DEF" ;;
*) echo "$DEF" ;;
esac
done
Run Code Online (Sandbox Code Playgroud)