【问题标题】:flag to overwrite download url command覆盖下载 url 命令的标志
【发布时间】:2012-06-25 17:29:01
【问题描述】:

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

目前,我有

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

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

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

【问题讨论】:

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


【解决方案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

【讨论】:

  • 所以在命令行中,我基本上会输入 sh myscript.sh -c cont?请告诉我
  • 不,只需bash myscript.sh -c 或者如果您将脚本标记为可执行文件 (chmod u+x myscript.sh) 并添加一个 shebang (#!/bin/bash) 作为第一行,那么您可以执行 ./myscript.sh -c跨度>
  • 对不起,再次问一个简单的问题,这个命令会做什么?如果 (( $? != 0 )) && !续;然后 echo -e "can't reach the url, \n aborting" exit fi
  • @user1477324:您可以将下载命令放在该部分之前。如果下载不成功且未指定-c 选项,则输出消息并退出。我已经编辑了我的答案以使其更清晰。
  • 对于选项,它将是 :ch: 或 :c:h: ?和 c ) cont=true;; h) 用法;出口;;有错字吗?我以为会是 h ) usage = exit;; ,这里的“h”有什么重要性?抱歉,我问你太多问题了,因为我对 getopts 一无所知,但我非常感谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 2021-06-26
相关资源
最近更新 更多