Bash如何检测传递给脚本的缺少必需参数 [英] Bash how to detect missing mandatory arguments passed to a script

查看:59
本文介绍了Bash如何检测传递给脚本的缺少必需参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Bash脚本,我需要传递一定数量的参数以使其起作用.

./upload.sh $ ARG1 $ ARG2 $ ARG3

假设2个必填字段是ARG1和ARG2,并且
ARG1和3不为空.

I have a Bash script and I need to pass a certain number of arguments to make it work.

./upload.sh $ARG1 $ARG2 $ARG3

Let's say that the 2 mandatory fields are ARG1 and ARG2, and
ARG1 and 3 are not empty.

我认为该脚本将运行并认为它具有2个强制性参数,有没有办法检测到ARG2丢失/为空?我需要返回出口1而不是出口0.

I think the script will run and think that it has the 2 mandatory arguments, Is there a way to detect that ARG2 is missing/empty? I need to return exit 1 and not exit 0.

这里有一些脚本

RESOURCE=$1
CONTAINER=$2
APP_NAME=$3

if [[ -z $RESOURCE || -z $CONTAINER ]];
then
    echo `date`" - Missing mandatory arguments: resource and container. "
    echo `date`" - Usage: ./upload.sh  [resource] [container] [appname] . "
    exit 1
fi

预先感谢

阿兰

推荐答案

我总是使用一个小函数来检查所有参数:

I always use a little function to check all the arguments:

process_arguments() {
    while [ -n "$1" ]
    do
        case $1 in
            -h|--help) echo "some usage details"; exit 1;;
            -x) do_something; shift; break;;
            -y) do_something_else; shift; break;;
            *) echo "some usage details"; exit 1;;
        esac
        echo $1; shift
    done
}

这样,如果您错过任何内容,将显示正确的用法详细信息,脚本将退出.否则,您可以按任何顺序输入参数.脚本启动后,只需调用

This way if you miss anything, the proper usage details will be displayed the script will exit. Otherwise, you can enter the args in any order. When your script starts, just call

process_arguments "$@"

您应该已经准备就绪.

这篇关于Bash如何检测传递给脚本的缺少必需参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆