用于覆盖下载url命令的标志

时间:2012-06-23 20:29:04

标签: bash shell command-line-arguments flags getopts

我对shell脚本很新,我必须在我的脚本中添加一个标志(getopts),如果脚本因任何原因无法访问url,我可以覆盖download url命令。例如,如果我添加了我的标志,那么它将不会终止我的脚本,如果无法访问url,我可以选择继续。

目前,我有

if "$?" -ne "0" then
echo "can't reach the url, n\ aborting"
exit

现在我需要通过getopts添加一个标记,我可以选择忽略"$?' - ne "0"命令,

我不知道getopts是如何工作的,我对它很陌生。有人可以帮我解决一下这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果您只有一个选项,有时只需检查$1

就更简单了
# put download command here
if (( $? != 0 )) && [[ $1 != -c ]]; then
    echo -e "can't reach the url, \n aborting"
    exit
fi
# put stuff to do if continuing here

如果您要接受其他选项,有些可能带参数,则应使用getopts

#!/bin/bash
usage () { echo "Here is how to use this program"; }

cont=false

# g and m require arguments, c and h do not, the initial colon is for silent error handling
options=':cg:hm:' # additional option characters go here
while getopts $options option
do
    case $option in
        c  ) cont=true;;
        g  ) echo "The argument for -g is $OPTARG"; g_option=$OPTARG;; #placeholder example
        h  ) usage; exit;;
        m  ) echo "The argument for -m is $OPTARG"; m_option=$OPTARG;; #placeholder example
        # more option processing can go here
        \? ) echo "Unknown option: -$OPTARG"
        :  ) echo "Missing option argument for -$OPTARG";;
        *  ) echo "Unimplimented option: -$OPTARG";;
    esac
done

shift $(($OPTIND - 1))

# put download command here
if (( $? != 0 )) && ! $cont; then
    echo -e "can't reach the url, \n aborting"
    exit
fi
# put stuff to do if continuing here