繁体   English   中英

Shell:使用getopts设置可选参数或使用默认值?

[英]Shell: Set optional argument or use default value using getopts?

我正在尝试将以下内容作为我的脚本的有效调用:

sh name.sh -l -a
sh name.sh -l

这是我到目前为止使用getopts的代码,其中-a是必需的参数:

default="no"

echo "Initial parameters. 

while getopts ":l:a:" o; do
    case "${o}" in
        l)
            ...;;
        a)
            a+=(${OPTARG})
            IFS=',' read -a myarray <<< "$a"
            default="yes"
            ;;
        :)
            echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *)
            usage;;
    esac
done
shift $((OPTIND-1))

if [ -z "${l}" ] || [ -z "${a}" ] ; then
    usage
fi

我只需要知道如何在getopts中设置可选标志-a和它的参数。 谢谢:)

据我所知, getopts不支持可选的option-arguments。 您可以通过自己处理option-argument来解决此问题:

#!/bin/bash

while getopts "x" o; do
  case "${o}" in
    x)
      OPTARG=${!OPTIND}

      if [ "${OPTARG:0:1}" == "-" ] || [ "$#" -lt "$OPTIND" ]; then
        OPTARG="DEFAULT"
      else
        OPTIND=$(( $OPTIND + 1 ))
      fi

      echo $OPTARG
      ;;
  esac
done

暂无
暂无

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

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