1

我有一个问题,当我选择一个选项时,例如 ./test.sh -f 它应该打印“mel”,但它会读取所有代码。

它如何进入 if 条件并与其他参数一起传递?

if getopts :f:d:c:v: arg ; then

if [[ "${arg}" == d ]]  ; then
    d_ID=$OPTARG
    eval d_SIZE=\$$OPTIND
else
            echo "Option -d argument missing: needs 2 args"
            echo "Please enter two args: <arg1> <arg2>"
            read d_ID d_SIZE
            echo "disc $d_ID $d_SIZE" >> $FILENAME

fi


if [[ "${arg}" == c ]] ; then
    c_NOME="$OPTARG"
    eval c_ID1=\$$OPTIND 
    eval c_ID2=\$$OPTINDplus1 
    eval c_FICHEIRO=\$$OPTINDplus2 
else
            echo "Option -c argument missing: needs 4 args"
            echo "Please enter two args: <arg1> <arg2> <arg3> <agr4>"
            read c_NOME c_ID1 c_ID2 c_FICHEIRO
            echo "raidvss $c_NOME $c_ID1 $c_ID2 $c_FICHEIRO" >> $FILENAME

fi

if [[ "${arg}" == f ]] ; then
    echo "mel"

fi


fi
4

1 回答 1

2

您使用的getopts参数错误。

if getopts :f:d:c:v: arg

表示-f将遵循参数的值,例如

-f 5

如果您只想拥有-f(没有价值),则需要将其更改为

if getopts :fd:c:v: arg ; then

(我删除了':')。另外,我认为您应该更好地使用while循环和case语句。

看这个例子

while getopts fd:c:v: opt
do
   case "$opt" in
      f) echo "mel";;
      d) discFunction "$OPTARG";;
      c) otherFunction "$OPTARG";;
      v) nop;;
     \?) echo "$USAGE" >&2; exit 2;;
   esac
done    

shift `expr $OPTIND - 1`
于 2013-10-06T12:52:30.643 回答