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

如何在bash的getopts中添加可选参数?,bash,getopts,Bash,Getopts,我想在getopts中添加两个可选参数。例如,对于下面的代码,我想添加两个可选参数-cagefile和knownlinc。如何通过修改此代码来做到这一点 while getopts ":b:c:g:hr:" opt; do case $opt in b) blastfile=$OPTARG ;; c) comparefile=$OPTARG ;; h) usage exit 1 ;;

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

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
    [ "$1" == "cagefile" ] && echo "cagefile found!"
    [ "$1" == "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!

您是否打算将长选项(例如
--help
)与短选项(例如
-h
)一起使用?如何将文件分配给
cagefile
knownlinc
?基本上我想像这样运行我的脚本
sh evolinc-part-I.sh-c cuffcompare.gtf-g Brassica_genome.fa-r Brassica_cds.fa-b TE_transcripts.fa
(这些都是强制参数)和-t Brassica_cage.gtf(cagefile)和-x Brassica_known.gff(这两个是可选的)`我不明白。我认为你混淆了选项和论点。类似cmd的
test.sh-t-A test
有两个选项
t
A
,但只有
A
有一个参数。如果在getopts中定义类似于
getopts“t:“opt
的内容,
t
的参数已经是必需的。