1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルで"問答形式(Yes/No)" or "全てYes(-y, -Y)"

Last updated at Posted at 2016-11-10

シェルスクリプトをそのまま実行した場合、"yes, Yes, YES, y, Y"の 5パターンに一致した場合は処理は継続され、"no, No, NO, n, N"の5パターンに一致した場合は処理はスキップ。

そしてシェルスクリプトのオプションに"-y, --yes"を指定した場合は、全て自動でYesが応答される処理を実装してみた。

以下、ソースコード。

yes_or_no.sh
#!/bin/bash
# ==================================================================
# オプションチェック
# ==================================================================
FLAG_Y=0
for OPT in "$@"
do
    case "$OPT" in
        '-y' | '--yes')
            FLAG_Y=1
            ;;
        '-h' | '--help')
            echo "Usage: $0 [-y, --yes] [-h, --help]"
            echo ""
            echo "optional arguments:"
            echo "  -y, --yes      answer all yes"
            echo "  -h, --help     show this help message and exit"
            ;;
    esac
done
shift $((OPTIND - 1))

# ==================================================================
# 実行内容
# ==================================================================
[ ${FLAG_Y} -eq 0 ] && echo "処理を実行しますか?[Y/N]"
while true;
do
  [ ${FLAG_Y} -eq 1 ] && READ_ANSWER="yes" || read READ_ANSWER
  case ${READ_ANSWER} in
    # yes, Yes, YES, y, Y の 5 パターンに一致。
    [yY]es | YES | [yY]) echo 'Yesが入力されました。処理を実行します。'
    # ==============================================================
      echo "yes, Yes, YES, y, Y が応答されました。";
    # ==============================================================
    break ;;
    # no, No, NO, n, N の 5 パターンに一致。
    [nN]o | NO | [nN]) echo "Noが入力されました。処理を終了します。"
    break ;;
    # 全ての文字列に一致。
    # つまり上記 6 パターンの何れでもない文字列が入力された場合の処理となる。
    * ) echo "YesかNoを入力してください。" ;;
  esac
done

exit 0
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?