getopts 空参数和默认值

问题描述 投票:0回答:2

我的要求非常简单,我只是想检查

getopts
参数是否为空。我正在使用詹金斯踢我的脚本,并且需要检查提供的值是否为空,然后设置默认值,否则使用提供的值:

并将参数传递给 shell 脚本,如下所示:

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

来自 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}"

当我开始这份工作时,它并没有给我想要的结果:

如何使用

getopts
来检查参数是否为空,而不是分配执行某些操作的默认值,否则使用提供的参数值。

linux bash shell getopts
2个回答
0
投票

它并不真正在 getopts 内,但是如果变量为空或不为空,您可以让 shell 以不同的方式扩展变量,例如

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

或者,您可以只检查 OPTARG 是否为空并继续,或者在整个循环后设置默认值,例如当且仅当它之前为空时,其中任何一个都会设置 SOURCE_SNAPSHOT_ID

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

有关此类变量用法的更多信息,请参阅 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.

0
投票

测试一下:

  • 分配一个变量
Z) testarg=$OPTARG
    ;;
  • 测试变量
if [ -z "$testarg" ]; then $(set default value); fi
© www.soinside.com 2019 - 2024. All rights reserved.