我想在 getopt bash 中将参数设置为可选,这样如果用户没有指定它,它仍然可以运行而不会终止程序。我怎样才能做到这一点。这是我之前的代码
while getopts ":l:q:s:e:hg:" opt; do
case $opt in
l)
lincRNAfasta=$OPTARG
;;
q)
query_species=$OPTARG
;;
s)
subject_species=$OPTARG
;;
e)
subject_gff=$OPTARG
;;
h)
echo "USAGE : open script in text editor"
exit 1
;;
g)
subject_genome=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
抱歉,必须更新我的答案,我误解了这个问题。
我正在查看
getopts.c
的文档,它确实支持 ::
但是无论我指定 1、2 还是 3 个参数,并且以任何顺序,您的代码都可以工作。
如果退出时出现错误,原因之一可能是需要定义变量:
#! /bin/bash
lincRNAfasta=
query_species=
subject_species=
subject_gff=
subject_genome=
help='''
USAGE : open script in text editor
-l lincRNAfasta
-q query_species
-s subject_species
-e subject_gff
-g subject_genome
'''
while getopts ":l:q:s:e:hg:" opt; do
case $opt in
l)
lincRNAfasta=$OPTARG
;;
q)
query_species=$OPTARG
;;
s)
subject_species=$OPTARG
;;
e)
subject_gff=$OPTARG
;;
h)
printf "$help"
exit 1
;;
g)
subject_genome=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
echo "doing something else"
if [ -z "$lincRNAfasta" ];then
echo "its empty"
echo "lincRNAfasta: $lincRNAfasta"
echo
else
echo "not empty"
echo "lincRNAfasta: $lincRNAfasta"
echo
fi
if [ -z "$query_species" ];then
echo "its empty"
echo "query_species: $query_species"
echo
else
echo "not empty"
echo "query_species: $query_species"
echo
fi
if [ -z "$subject_species" ];then
echo "its empty"
echo "subject_species: $subject_species"
echo
else
echo "not empty"
echo "subject_species: $subject_species"
echo
fi
if [ -z "$subject_gff" ];then
echo "its empty"
echo "subject_gff: $subject_gff"
echo
else
echo "not empty"
echo "subject_gff: $subject_gff"
echo
fi
if [ -z "$subject_genome" ];then
echo "its empty"
echo "subject_genome: $subject_genome"
echo
else
echo "not empty"
echo "subject_genome: $subject_genome"
echo
fi
# do something once variables have been set
# any variable not set will be empty
echo "doing something else"
输出:
bob@squids:~/Desktop$ ./1.sh -h
USAGE : open script in text editor
-l lincRNAfasta
-q query_species
-s subject_species
-e subject_gff
-g subject_genome
bob@squids:~/Desktop$ ./1.sh -s a -g h -e e -q q
doing something else
its empty
lincRNAfasta:
not empty
query_species: q
not empty
subject_species: a
not empty
subject_gff: e
not empty
subject_genome: h
doing something else
bob@squids:~/Desktop$ ./1.sh -s a -g h -e e
doing something else
its empty
lincRNAfasta:
its empty
query_species:
not empty
subject_species: a
not empty
subject_gff: e
not empty
subject_genome: h
doing something else
bob@squids:~/Desktop$ ./1.sh -s a -e e -g 123
doing something else
its empty
lincRNAfasta:
its empty
query_species:
not empty
subject_species: a
not empty
subject_gff: e
not empty
subject_genome: 123
doing something else
或者您可以将变量初始化为“NOTSPECIFIEDONSTART”等字符串,而不是将变量初始化为空。当启动脚本时,您可以传递一个空字符串,例如
-g ''