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

时间:2016-08-30 12:45:32

标签: bash shell getopts

我写了以下的shellcript。我试图使用getopts方法从用户那里获得输入。这是我写的代码的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

2 个答案:

答案 0 :(得分:3)

while getopts "$options" opt
#             ^^       ^

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

答案 1 :(得分:2)

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

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

的Al

相关问题