如何在 Shell 脚本中传递命名参数

How to pass Named Parameter in Shell Script

下面是使用 getopts

的 shell 脚本
#!/bin/bash

while getopts "USER:PWD:JOBID:PROJECTID:" flag
do
         case "${flag}" in
                USER) TEST_USER=${OPTARG};;
                PWD) TEST_PWD=${OPTARG};;
                JOBID) TEST_JOBID=${OPTARG};;
                PROJECTID) TEST_PROJECTID=${OPTARG};;
         esac
       
done
echo "USER: $TEST_USER";
echo "PWD: $TEST_PWD";
echo "JOBID: $TEST_JOBID";                  
echo "PROJECTID: $TEST_PROJECTID"; 

Continue of script i have not put here and if above commands work fine then my issue solve 

这里是我 运行 在终端中输出的内容,哪一个是获取输出命令的正确方法

./getopts.sh -USER=devops@gmail.com -PWD=xxxxxx -JOBID=8a809e2496 -PROJECTID=80e2ea54b231f
OR
./getopts.sh USER=devops@gmail.com PWD=xxxxxx JOBID=8a809e2496 PROJECTID=80e2ea54b231f

在 运行 上面的命令之后,我收到空响应或字符串 用户: 残疾人士: 职位编号: 项目编号:

您可能需要阅读 getopts 手册页


    while getopts "U:P:J:I:" flag
    do
             case "${flag}" in
                    U) TEST_USER=${OPTARG};;
                    P) TEST_PWD=${OPTARG};;
                    J) TEST_JOBID=${OPTARG};;
                    I) TEST_PROJECTID=${OPTARG};;
             esac
    done
    echo "USER: $TEST_USER";
    echo "PWD: $TEST_PWD";
    echo "JOBID: $TEST_JOBID";
    echo "PROJECTID: $TEST_PROJECTID";
./getopts.sh -U devops@gmail.com -P xxxxxx -J 8a809e2496 -I 80e2ea54b231f
USER: devops@gmail.com
PWD: xxxxxx
JOBID: 8a809e2496
PROJECTID: 80e2ea54b231f

使用 getopt 更复杂,但它允许长选项和“=”。

    #!/bin/bash
    TEMP=$(getopt -n "[=13=]" -a -l "user:,password:,jobid:,projectid:" -- -- "$@")

    [ $? -eq 0 ] || exit

    eval set --  "$TEMP"

    while [ $# -gt 0 ]
    do
             case "" in
                    --user) TEST_USER=""; shift;;
                    --password) TEST_PWD=""; shift;;
                    --jobid) TEST_JOBID=""; shift;;
                    --projectid) TEST_PROJECTID=""; shift;;
                    --) shift;;
             esac
             shift;
    done
    echo "USER: $TEST_USER";
    echo "PWD: $TEST_PWD";
    echo "JOBID: $TEST_JOBID";
    echo "PROJECTID: $TEST_PROJECTID";

一些测试:

$ ./test.sh -user=jules -password=kabas -jobid 5555 -projectid 999 -c
./test.sh: unrecognized option '-c'

$ ./test.sh -user=jules -password=kabas -jobid 5555 -projectid 999   
USER: jules
PWD: kabas
JOBID: 5555
PROJECTID: 999