当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - For two consecutive options, `getopts` taking the second option as the argument of first

问题描述:

I have a code:

 while getopts ab:cde:f opt

do

case ${opt} in

b|e)

[[ ${OPTARG} = -* ]] && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"- ${opt}!\""

[[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"

;;

esac

case $opt in

a) minusa=$opt;;

b) minusb=$opt

file_b=$OPTARG;;

c) minusc=$opt;;

d) minusd=$opt;;

e) minuse=$opt

file_e=$OPTARG;;

f) minusf=$opt;;

/?) echo Unrecognized parameter

exit 1;;

esac

done

echo "minusa:$minusa","minusb:$minusb","file_b:$file_b","minusc:$minusc","minusd:$minusd","minuse:$minuse","file_e:$file_e","minusf:$minusf"

Simple code, just to understand the behavior of getopts command. When I run the script like:

 ./eg2 -b -f

./eg2: line 7: usage: command not found

minusa:,minusb:b,file_b:-f,minusc:,minusd:,minuse:,file_e:,minusf:

It is taking the argument for option -b as -f. Whereas I want to print:

 [[ ${OPTARG} = -* ]] && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"-${opt}!\""

Where exactly in the code I'm going wrong? Also for the options -b and -e if there is no arguments , I want to print:

 [[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"

Kindly explain.

网友答案:

You've put a ":" after the "b" in getopts line. That tells it to expect an argument afterwards. If you don't want the next argument to be treated like an argument to -b, remove that ":".

网友答案:

[[ "${OPTARG}" =~ "^-[a-z]" ]] && echo "Invalid parameter \"${OPTARG}\" provided for agurment \"-${opt}!\"" solves the problem...thanks

分享给朋友:
您可能感兴趣的文章:
随机阅读: