さまざまなユーザー入力に対して複数の検証ルールを処理する方法は?

さまざまなユーザー入力に対して複数の検証ルールを処理する方法は?

続行する前に、Bash スクリプトを使用して、ユーザーにいくつかの変数の入力を求めるメッセージを表示します。静的検証ルールを作成し、ユーザー入力に応じて「単体」として実行するにはどうすればよいですか?

例:

function q1 () {
  echo "Do you have an answer?"
  read input
  # I know this is wrong but should get the idea across
  chkEmpty($input)
  chkSpecial($input)
}

function chkEmpty () {

    if [[ $input = "" ]]; then
      echo "Input required!"
      # Back to Prompt
    else
      # Continue to next validation rule or question
    fi
}

function chkSpecial () {

    re="^[-a-zA-Z0-9\.]+$"
    if ! [[ $input =~ $re ]]; then
      echo "Cannot use special characters!"
      # Back to prompt
    else
      # Continue to next validation rule or question
    fi
}

function chkSize () {
    etc...
}

etc...

ベストアンサー1

$1この関数はパラメータ$2などを取得します。また、シェルでは括弧なしで呼び出されるため、コードは次のようになります。ほぼ正しい。

あなたの関数の構文も正しくありません。括弧または単語を使用していますfunction。最後に、返された結果(プロセスの終了コードのように動作)を使用できますreturn

chkEmpty() {
    if [[ "$1" = "" ]]; then
      echo "Input required!"
      return 1 # remember: in shell, non-0 means "not ok"
    else
      return 0 # remember: in shell, 0 means "ok"
    fi
}

これで、次のように呼び出すことができます。

function q1 () {
  echo "Do you have an answer?"
  read input
  chkEmpty $input && chkSpecial $input # && ...
}

たとえば、メッセージを再表示したりスクリプトを中断したりするなど、誤った入力を処理するには、いくつかのコードを追加する必要があります。while/untilとを使用している場合は、if関数の戻り値を確認して再度プロンプトまたは終了します。

おすすめ記事