简体   繁体   English

getopts 空参数和默认值

[英]getopts empty argument and default value

my requirement is really simple, I just want to check that if the getopts argument is empty or not.我的要求非常简单,我只想检查getopts参数是否为空。 I am kicking my script using the jenkins and need to check that if the provided value is empty then set the default otherwise use the provided value:我正在使用 jenkins 踢我的脚本,需要检查提供的值是否为空,然后设置默认值,否则使用提供的值: 在此处输入图片说明

and passing the arguments to the shell script like this:并将参数传递给 shell 脚本,如下所示:

./rds-db-dump.sh -s ${source_instance_id}  -c ${target_instance_class} -i ${source_snapshot_id}

snippet from shell script:来自shell脚本的片段:

while getopts ":s:c:i:h" opt; do
  case ${opt} in
    s) SOURCE_INSTANCE_ID="${OPTARG}"
    ;;
    c) TARGET_INSTANCE_CLASS="${OPTARG}"
    ;;
    i) SOURCE_SNAPSHOT_ID="${OPTARG}"
    ;;
    h) usage && exit 1
    ;;
    \?) echo "Invalid option -${OPTARG}" >&2
    usage && exit 1
    ;;
  esac
done

echo "SOURCE_SNAPSHOT_ID: ${SOURCE_SNAPSHOT_ID}"
echo "TARGET_INSTANCE_CLASS: ${TARGET_INSTANCE_CLASS}"

when I kicked off this job, it doesn't give me desired result:当我开始这份工作时,它并没有给我想要的结果: 在此处输入图片说明

How I can achieve that with getopts to check if the argument is empty than assign some default value of perform some operation otherwise use the provided value of argument.我如何使用getopts来检查参数是否为空,而不是分配一些默认值来执行某些操作,否则使用提供的参数值。

It's not really within getopts, but you can have your shell expand the variable differently if it is empty or not eg 它不是真正在getopts内,但是您可以让您的shell以不同的方式扩展该变量(如果它为空),例如

    i) SOURCE_SNAPSHOT_ID="${OPTARG:-yourdefaultvalue}"

Alternatively you can just check if OPTARG is empty and continue, or set default values after the whole loop eg either of these would set SOURCE_SNAPSHOT_ID if and only if it was empty before 或者,您可以仅检查OPTARG是否为空并继续,或者在整个循环后设置默认值,例如,当且仅当它之前为空时,这两个值中的任何一个都会设置SOURCE_SNAPSHOT_ID

: ${SOURCE_SNAPSHOT_ID:=yourdefaultvalue}
SOURCE_SNAPSHOT_ID=${SOURCE_SNAPSHOT_ID:-yourdefaultvalue}

See the "Parameter Expansion" of the bash manual for more information on such variable usage (only quoting the two I used): 有关此类变量用法的更多信息,请参见bash手册的“参数扩展”(仅引用我所使用的两个变量):

   ${parameter:-word}
          Use  Default  Values.   If  parameter is unset or null, the expansion of word is substituted.
          Otherwise, the value of parameter is substituted.
   ${parameter:=word}
          Assign Default Values.  If parameter is unset or null, the expansion of word is  assigned  to
          parameter.   The  value  of parameter is then substituted.  Positional parameters and special
          parameters may not be assigned to in this way.

just test it:测试一下:

  • assign a variable分配一个变量
Z) testarg=$OPTARG
    ;;
  • test the variable测试变量
if [ -z "$testarg" ]; then $(set default value); fi

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

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