bash getopts使用户输入尽可能地出错

时间:2015-04-10 13:45:54

标签: bash unix getopts

我的一个脚本中有以下代码。我试图尽可能地将用户用作错误证明。

while getopts ":c:d:t:T:a:" opt; do
        case ${opt} in
                c )
                        currency=$OPTARG
                        ;;
                d )
                        cdate=$OPTARG
                        ;;
                t )
                        terms_arr=$OPTARG
                        ;;
                T )
                        tails_arr=$OPTARG
                        ;;
                a )
                        all=$OPTARG
                        ;;
                \? )
                        echo "Invalid Option: -$OPTARG" 1>&2
                        echo "Usage: -c [currency USD/JPY,U/J] -d [YYYYMMDD] -t [comma-sep list]\
                        -T [comma-sep list] -a [duplicate rows y/n]"
                        echo "  e.g. -c JPY -d 20150220 -t 1,2,3 -T 7,10,15 -a y"
                        exit 1
                        ;;
                : )
                        echo "Used option defaults......."
                        ;;
        esac
done

shift $((OPTIND -1))

if ! date -d "$cdate" >/dev/null 2>&1; then
        echo "error: Incorrect date specified.Correct format is YYYYMMDD.Please try again."
        exit 1
elif [ -z "$cdate" ]
then
        cdate=$(date +"%Y%m%d")
fi

if [ "$currency" = "JPY" ] || [ "$currency" = "J" ] || [ "$currency" = "j" ]
then
        currency="JPY"

elif [ "$currency" = "USD" ] || [ "$currency" = "U" ] || [ "$currency" = "u" ] || [ -z "$currency" ]
then
        currency="USD"

else
        echo "error: Currency should be USD/JPY" >&2
        exit 1
fi

if [ -z "$terms_arr" ]
then
        terms_arr="1,2,3"
elif ! [[ $terms_arr =~ ^([0-9]+,?)+$ ]]
then
        echo "error: terms $terms_arr.. can only be comma separated numbers. Please try again." >&2
        exit 1
fi

if [ -z "$tails_arr" ]
then
        tails_arr="7,10,15"
elif ! [[ $tails_arr =~ ^([0-9]+,?)+$ ]]
then
        echo "error: tails $tails_arr.. can only be comma separated numbers. Please try again." >&2
        exit 1
fi

if [ -z "$all" ]
then
        all="n"
fi

这样可以正常工作,直到有一些不好的输入。

-c J 20150222 -a yyyyymmdd日期未输入-d)使-a值未使用。 (默认'n')。使用此输入,我需要将货币-c设为'JPY',但未输入的任何选项(- d, -t, -T)应采用if条件中的默认值,然后取-a值{{ 1}}输入。

'y'

还想知道是否所有这些都可以通过我错过的任何其他检查以更好的方式完成。

我知道-c J -t 1,2;3 -T 7;10,15 -a y for comma separated lists -t, -T if I enter as shown (; typed in place of , ) the program exits with the message: If '3' is not a typo you can run the following command to lookup the package that contains the binary: command-not-found 3 -bash: 3: command not found If '10,15' is not a typo you can run the following command to lookup the package that contains the binary: command-not-found 10,15 不支持默认值。

长篇大论道歉。

0 个答案:

没有答案