1

我对 shell 脚本很陌生,我必须在getopts我的脚本中添加一个标志 (),如果脚本由于任何原因无法到达 url,我可以在其中覆盖下载 url 命令。例如,如果我添加我的标志,那么它不会终止我的脚本,如果无法访问 url,我可以选择继续。

目前,我有

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

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

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

4

1 回答 1

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
于 2012-06-23T20:44:38.930 回答