2013-10-06 157 views
1

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

它是如何进入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 

回答

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` 
相关问题