Bash 不带可选参数的GETOPTS大小写
您好,我正在试图找到一种方法,如何使getopts与非预期的可选参数一起工作 我有一个带有可选参数的脚本Bash 不带可选参数的GETOPTS大小写,bash,Bash,您好,我正在试图找到一种方法,如何使getopts与非预期的可选参数一起工作 我有一个带有可选参数的脚本 script.sh [-a] [-b] [-c | -d] file 我有一个…我喜欢这个 while geopts abc:abd opt do case $opt in a) do this ;; b) do this ;; ... script.sh file 。。等 我想让它在没有这些参数的情况下工作,这样我就可以像这样运行它 while geopts abc:abd opt
script.sh [-a] [-b] [-c | -d] file
我有一个…我喜欢这个
while geopts abc:abd opt
do
case $opt in
a) do this ;;
b) do this ;;
...
script.sh file
。。等
我想让它在没有这些参数的情况下工作,这样我就可以像这样运行它
while geopts abc:abd opt
do
case $opt in
a) do this ;;
b) do this ;;
...
script.sh file
有没有一种方法可以创建一个新的案例选项,或者我需要用其他方法来做呢?谢谢大家的帮助,我是bash的初学者。我以前做过这种事情:
declare -A have=([a]=false [b]=false [c]=false [d]=false)
while geopts :abcd opt; do
case $opt in
a) have[a]=true ;;
b) have[b]=true ;;
c) have[c]=true ;;
d) have[d]=true ;;
?) echo "illegal option: -$OPTARG"; exit 1;;
esac
done
shift $((OPTIND-1))
if ${have[c]} && ${have[d]}; then
echo "cannot give both -c and -d"
exit 1
fi
${have[a]} && do_a_stuff
${have[b]} && do_b_stuff
...
这个case语句是一个相当惊人的cut'n'paste编程:收紧它:
while geopts :abcd opt; do
case $opt in
a|b|c|d) have[$opt]=true ;;
?) echo "illegal option: -$OPTARG"; exit 1;;
esac
done
我有以下测试脚本:
#! /bin/bash
USAGE="test.sh [-a] [-b] [-c | -d ]"
while getopts :abcd option
do
case $option in
a) OPT_A=1;;
b) OPT_B=1;;
c) OPT_C=1;;
d) OPT_D=1;;
*)
echo "$OPTARG is not a valid option."
echo "$USAGE"
exit 2;;
esac
done
shift $((OPTIND-1))
if [[ $OPT_C && $OPT_D ]]
then
echo "That's a no-no using options c and d together"
echo "$USAGE"
exit 2
fi
echo "The following options were set"
[[ $OPT_A ]] && echo " Option A was set"
[[ $OPT_B ]] && echo " Option B was set"
[[ $OPT_C ]] && echo " Option C was set"
[[ $OPT_D ]] && echo " Option D was set"
echo "And the file name is $1"
它将向您显示设置了哪些选项(哪些未设置)。它测试以确保-c
和-d
没有一起使用
不是100%确定你想要什么。但是,您可以看到,在我的
case
语句中并没有这样说,我只是设置变量来显示哪些选项被选中或未被选中。这本身就解决了您的问题。您是否在考虑shell脚本的默认操作?(在我的书中,这是一个不错的策略)。在使用getopts进行处理之前,先设置默认值,然后通过getopts传入的任何值都会覆盖默认变量。否则你必须给我们更多关于你想要完成什么的细节。(不要以评论的形式回答,添加到上面的问题中)。祝你好运