1

スクリプトの 1 つの問題を解決するのに助けが必要です。オプション ( c、e 、 d、f 、および g) はスクリプトの必須オプションであり、スクリプトを実行する前に常に暗示されます。それ以外の場合、スクリプトは実行されません。コマンドを追加しました。必要なパラメータを指定せずにスクリプトを実行しようとすると、スクリプトは実行されて終了します。必要なパラメータを渡さずにスクリプトを実行するべきではありませんが、実行して終了します。 . どうすればこれを修正できますか?

前もって感謝します、

#!/bin/bash


cont=false


options=':c:d:e:f:g:h:i' # additional option characters go here
while getopts $options option
do
    case $option in
        c  ) cont=true;;
        d  ) hello="$OPTARG"
        e  ) hi="$OPTARG"
        f  ) Fri="$OPTARG"
        g  ) Sat="$OPTARG"
        h  ) SUN="$OPTARG"
        i  ) ....so on
        # more option processing can go here

    esac
done

shift $(($OPTIND - 1))
4

2 に答える 2

1

必要なオプションを含むと呼ばれる配列を使用し、指定されたオプションに対してmandatory配列要素をに設定すると-、以下のコードは、指定されていない必須オプションのエラーを報告します。

mandatory=(c d e f g)
options=':c:d:e:f:g:h:i'
while getopts $options option
do
  for ((i = 0 ; i < ${#mandatory[@]} ; i++ )); do
    [[ $option == ${mandatory[$i]} ]] && mandatory[$i]="-"  
  done
  case $option in
      c  ) echo c; cont=true;;
      d  ) hello="$OPTARG";;
      e  ) hi="1"
  esac
done

for ((i = 0 ; i < ${#mandatory[@]} ; i++ )); do
  if [[ ${mandatory[$i]} != '-' ]]; then
    echo "option ${mandatory[$i]} was not given"
    exit 1
  fi
done

if cat /proc/mounts | grep /dev ; then echo "mount exists
   else
   echo "mount doesn't exist"
   exit ; 
fi 
于 2012-07-30T04:03:53.870 に答える
1

Since you have a colon in front of the options, it is your responsibility to handle the error condition.

From help getopts:

If the first character of OPTSTRING is a colon, getopts uses silent error reporting. In this mode, no error messages are printed. If an invalid option is seen, getopts places the option character found into OPTARG. If a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found.

You must handle the case where $option contains :.

于 2012-07-30T03:34:05.327 に答える