代码之家  ›  专栏  ›  技术社区  ›  Arbab Nazar

getopts空参数和默认值

  •  0
  • Arbab Nazar  · 技术社区  · 7 年前

    我的要求很简单,我只想检查一下 getopts 参数是否为空。我正在使用jenkins踢我的脚本,需要检查提供的值是否为空,然后设置默认值,否则使用提供的值: enter image description here

    并将参数传递给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}"
    

    当我开始这项工作时,它没有给我期望的结果: enter image description here

    我怎样才能做到 获取选项 若要检查参数是否为空,请指定“执行某些操作”的默认值,否则请使用提供的参数值。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Asmadeus    7 年前

    它实际上并不在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.
    
    推荐文章