GetOpts 未将指定的选项识别为有效



我写了下面的shellscript。我正在尝试使用 getopts 方法从用户那里获取输入。这是我编写的代码片段。

#Define the help function
function help(){
    echo "Options:";
    echo "-u    Github username"
    echo "-p    Github password"
    echo "-r    Repository name"
    echo "-s    Service name"
    echo "-b    Branch name (Default master)"
    exit 1;
}

#Initialize the default values for the variables.
username="username";
password="password";
rname="rname";
sname="sname";
branch="master";
#Define the getopts variables
options="u:p:r:s:h";
#Start the getopts code
while getopts options opt; do
    case $opt in
            u) #Get the username
                    username=$OPTARG
            ;;
            p) #Get the password
                    password=$OPTARG
            ;;
            r) #Get the repository name
                    rname=$OPTARG
            ;;
            s) #Get the service name
                    sname=$OPTARG
            ;;
            b) #Get the branch name
                    branch=$OPTARG
            ;;
            h) #Execute the help function
        "echo here"
                    help;
            ;;
            ?) #unrecognized option - show help
                    echo "Invalid option."
                    help;
            ;;
    esac
done
#This tells getopts to move on to the next argument.
shift $((OPTIND-1))
#End getopts code

我尝试通过以下方式启动脚本:

./testScript.sh -u myname

我收到以下错误:

illegal option -- u
while getopts "$options" opt
#             ^^       ^

$替换变量的值 options 。 如果没有$getopts认为有效的标志是 -o, -p, -t, -i, -n 和 -s。

您忘记了选项前面的美元符号,以将其视为变量:

 #Start the getopts code
 while getopts $options opt; do

最新更新