如何在 bash 中的 getopts 中添加可选参数?

How to add optional arguments in getopts in bash?

我想在 getopts 中添加几个可选参数。例如,对于下面的代码,我想添加 2 个可选参数 - cagefileknownlinc。我如何通过修改此代码来做到这一点?

while getopts ":b:c:g:hr:" opt; do
  case $opt in
    b)
      blastfile=$OPTARG
      ;;
    c)
      comparefile=$OPTARG
      ;;
    h)
      usage
      exit 1
      ;;
    g)
     referencegenome=$OPTARG
      ;;
    r)
     referenceCDS=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

一个支持 longopts 的简单解决方案是在 getopts 命令后手动解析剩余参数。像这样:

#!/bin/bash

# parse basic commands (only example) 
while getopts "t:" opt; do
    case "$opt" in
    t)  TVAR="$OPTARG"
        ;;
    *)  echo "Illegal argument."; exit 1
        ;;
    esac
done
echo "TVAR set to: $TVAR"

# shift to remaining arguments 
shift $(expr $OPTIND - 1 )

while test $# -gt 0; do
    [ "" == "cagefile" ] && echo "cagefile found!"
    [ "" == "knownlinc" ] && echo "knownlinc found!"
    shift
done

输出将是..

» ./test.sh
» ./test.sh -t
./test.sh: option requires an argument -- t
Illegal argument.
» ./test.sh -t 2
TVAR set to: 2
» ./test.sh -t 2 cagefile
TVAR set to: 2
cagefile found!
» ./test.sh -t 2 cagefile knownlinc
TVAR set to: 2
cagefile found!
knownlinc found!