这是我正在尝试做的事情
while getopts "h?rd" opt; do case "$opt" in h|\?) echo "invalid" exit 0 ;; r) report=1 ;; d) delete=1 ;; esac done
-r&-d工作,并且作为parameter passing的任何其他字符发出错误。 但如果我不使用参数,代码也运行。 我想要提示错误。 我怎样才能做到这一点?
您可以使用bash的$#
变量来查找没有参数。 也可以通过在getopts
使用case *)
来获得其他无效参数
#!/bin/bash if [ $# -lt 1 ]; then echo "no arguments" exit 1 fi while getopts ":h\?rd" opt; do case "$opt" in h|"\?") echo "valid" exit 0 ;; r) report=1 ;; d) delete=1 ;; *) echo "not valid" ;; esac done
但如果我不使用参数,代码也运行。
getopts无法帮助你。 你可以放
if [ -z "$@" ] then echo "No arguments entered.. >&2 echo "Usage command -[h|?|r|]" >&2 exit 1 fi
在开始处理这种情况。
另外我会建议对脚本做一些小的修改,如下所示:
#!/bin/bash while getopts ":hr:d" opt; do #adding a colon in the beginning of the optstring supresses the #system generated error message for invalid options. case "$opt" in h) echo "Help Stuff" ;; r) report=1 echo $report ;; d) delete=1 echo $delete ;; \?) echo "Invalid option $OPTARG" echo "Aborting.." exit 1 >&2 # Once an invalid option found abort esac done shift # Checking for non-option arguments. [[ $1 = "--" ]] && shift #Non option arguments begin with a --, So you need to 'shift' once more lastparams=("$@") echo "${lastparams[@]}"
注意
标准文件desctiptors是0(标准输入),1(标准输出)和2(标准错误)。 你可以用/dev/stderr
替换&2
。