2012-06-23 65 views
1

我很新的shell脚本,我必须添加一个标志(getopts)到我的脚本,我可以覆盖下载url命令,如果脚本无法达到任何原因的网址。例如,如果我添加我的标志,那么它不会终止我的脚本,如果无法到达URL,我可以选择继续。标志覆盖下载url命令

目前,我有

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

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

我不知道getopts的是如何工作的,我非常新到它。有人可以帮助我如何去解决它吗?

+0

请参阅此链接了解有关getopts的文档:http://linux.about.com/library/cmd/blcmdl1_getopts.htm –

+0

@DexterHuinda:这只是[Bash'man'页面的一部分](http:// tiswww .case.edu/PHP /切特/庆典/ bash.html#lbDB)。这是一个很好的参考:[BashFAQ/035](http://mywiki.wooledge.org/BashFAQ/035)。 –

回答

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 
+0

所以在命令行中,我基本上输入sh myscript.sh -c cont?请让我知道 – user1477324

+0

不,只是'bash myscript.sh -c',或者如果您将脚本标记为可执行文件('chmod u + x myscript.sh')并添加一个shebang('#!/ bin/bash')作为第一行,然后你可以执行'./myscript.sh -c' –

+0

对不起,快速的问题,这个命令会做什么?如果(($?!= 0))&&!续;然后 echo -e“无法到达URL,\ n正在中止” 退出 fi – user1477324