简体   繁体   English

getopts:无法识别参数

[英]getopts: unable to identify arguments

This is the script I tried: 这是我尝试的脚本:

#!/bin/bash
while getopts ":u:p:" option; do
        case $option in
                u) USER=$OPTARG;;
                p) PASS=$OPTARG;;
                \?) echo "Invalid Option: $OPTARG"
                    exit 1;;
                :) echo "Please provide an argument for $OPTARG!"
                   exit 1;;
        esac
done
echo "Username/Password: $USER/$PASS"

If command for running the script is: 如果用于运行脚本的命令为:

./test9.sh -u test -p -a

Then I am getting an output: 然后我得到一个输出:

Username/Password: test/-a

-a is an invalid argument but the script is taking -a as password. -a是无效的参数,但是脚本使用-a作为密码。 I would like to display a message Please enter a password and exit the script. 我想显示一条消息, Please enter a password并退出脚本。 Please help me in fixing this. 请帮助我解决此问题。

There are three kinds of parameters: options, option arguments, and positional parameters. 参数共有三种:选项,选项参数和位置参数。 If a parameter is an option that requires an argument, then the next parameter will be treated as an an argument no matter what. 如果参数是需要参数的选项,则无论如何都将下一个参数视为参数。 It may start with a dash or even coincide with a valid option, it will still be treated as an option argument. 它可能以破折号开头,甚至与有效选项重合,但仍将被视为选项参数。

If your program wants to reject arguments that start with a dash, you need to program it yourself. 如果您的程序要拒绝以破折号开头的参数,则需要自己进行编程。 Passwords that start with a dash are perfectly legitimate; 以破折号开头的密码是完全合法的; a program that checks passwords must not reject them. 检查密码的程序不得拒绝它们。

Option that accept optional arguments are extremely confusing and non-standard. 接受可选参数的选项非常混乱且不规范。 Getopt in general doesn't support them. Getopt通常不支持它们。 There's a GNU extension for that, but don't use it. 有一个GNU扩展,但是不要使用它。

TL;DR there's nothing to fix, your script is fine. TL; DR没有要修复的内容,您的脚本很好。

我尚未测试您的脚本,但我认为,如果使用getopt而不是getopts ,则会得到您期望的结果,这是一个错误,因为-a不是有效的选项。

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

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