我想在getopts中添加几个可选参数。例如,对于以下代码,我想添加2个可选参数 - 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
答案 0 :(得分:3)
支持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!