简体   繁体   English

使用GetOpts和必需参数验证命令行参数

[英]Command line arguments validation with GetOpts and mandatory parameters

I'm creating a basic script that should take 3 mandatory command line options and each one must be followed by a value. 我正在创建一个基本脚本,该脚本应该采用3个强制命令行选项,每个选项必须后跟一个值。 Like this: 像这样:

$ myscript.sh -u <username> -p <password> -f <hosts.txt>

I'm trying to make sure the user is passing those exact 3 options and their values and nothing else, otherwise I want to print the usage message and exit. 我正在尝试确保用户正在传递那些确切的3个选项及其值,而不是其他内容,否则我想打印使用消息并退出。

I've been reading on getopts and came up with this: 我一直在阅读关于getopts并且想出了这个:

usage () { echo "Usage : $0 -u <username> -p <password> -f <hostsFile>"; }

if [ $# -ne 6 ]
then
        usage
        exit 1
fi

while getopts u:p:f: opt ; do
   case $opt in
      u) USER_NAME=$OPTARG ;;
      p) USER_PASSWORD=$OPTARG ;;
      f) HOSTS_FILE=$OPTARG ;;
      *) usage; exit 1;;
   esac
done

echo "USERNAME: $USER_NAME"
echo "PASS: $USER_PASSWORD"
echo "FILE: $HOSTS_FILE"

I was hoping that if I do not pass any of my 3 "mandatory" options (ie: -u -p -f) Optargs validation would catch that via the " *) " case. 我希望如果我没有通过任何我的3个“强制”选项(即:-u -p -f),Optargs验证将通过“ *) ”案例捕获。 While that is true for other options such "-a","-b", etc.. does not seem to be the case in this particular case: 虽然对于其他选项来说也是如此,例如“-a”,“ - b”等......在这种特殊情况下似乎并非如此:

$ myscript.sh 1 2 3 4 5 6

Getops does not treat that as invalid input and the script moves on executing the echo commands showing 3 empty variables. Getops不会将其视为无效输入,脚本会在执行显示3个空变量的echo命令时移动。

How can I capture the input above as being invalid as it is not in the form of: 如何将上面的输入捕获为无效,因为它不是以下形式:

$ myscript.sh -u <username> -p <password> -f <hosts.txt>

Thanks! 谢谢!

getopts has no concept of "mandatory" options. getopts没有“强制”选项的概念。 The colons in u:p:f: mean that, if one of those options happens to be supplied, then an argument to that option is mandatory. u:p:f:的冒号u:p:f:表示如果恰好提供了其中一个选项,那么该选项的参数是必需的。 The option-argument pairs, however, are always optional. 但是,选项 - 参数对始终是可选的。

You can require that the user provide all three though with code such as: 您可以要求用户提供所有三个代码,例如:

if [ ! "$USER_NAME" ] || [ ! "$USER_PASSWORD" ] || [ ! "$HOSTS_FILE" ]
then
    usage
    exit 1
fi

Place this code after the while getopts loop. 将此代码放在while getopts循环之后。

The Role of *) *)的作用

I was hoping that if I do not pass any of my 3 "mandatory" options (ie: -u -p -f) Optargs validation would catch that via the "*)" case. 我希望如果我没有通过任何我的3个“强制”选项(即:-u -p -f),Optargs验证将通过“*)”案例捕获。

The *) case is executed only if an option other than -u , -p , or -f is supplied. 只有在提供-u-p-f 以外的选项时才执行*)情况。 Thus, if someone supplied, for example a -z argument, then that case would run. 因此,如果某人提供了例如-z参数,那么该情况就会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM