我怎样才能使用getopts
不带参数的?
while getopts ":a:f:l:r:h:v:" arg; do
printf $arg
case $arg in
a)
add_param=${OPTARG}
;;
f)
file_param=${OPTARG}
;;
l)
list_param=${OPTARG}
;;
r)
remove_param=${OPTARG}
;;
v)
version_param="version"
printf "hello world"
;;
h | *)
print_usage
exit_script
esac
done
-v
如果我像这样运行我的脚本,我永远不会遇到这种情况,sh script.sh -v
因为这个实现需要一个参数。
你能帮我解决这个问题吗?
答案1
来自help getopts
(在bash
):
getopts: getopts optstring name [arg] Parse option arguments. Getopts is used by shell procedures to parse positional parameters as options. OPTSTRING contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
我认为 也适用于sh
。您应该尝试":a:f:l:r:hv"
而不是":a:f:l:r:h:v:"
。