bash输出无效选项

时间:2011-04-14 17:01:53

标签: linux bash switch-statement optional-parameters

假设我有以下脚本来处理选项:

while getopts dsf opts 2>/dev/null
do
    case $opts in
    d) echo "d";;
    s) echo "s";;
    \?) echo "Error: An invalid option [?] was entered.";
        exit 1;;
    esac
done

我想用我输入的无效开关替换[?]。 所以,如果我输入

./myscript -z //output: Error: An invalid option [-z] was entered.

如何捕获无效的开关?使用我的$ opts变量会显示一个问号。

1 个答案:

答案 0 :(得分:5)

来自help getopts

getopts reports errors in one of two ways.  If the first character
of OPTSTRING is a colon, getopts uses silent error reporting.  In
this mode, no error messages are printed.  If an invalid option is
seen, getopts places the option character found into OPTARG.