2
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 1 year has passed since last update.

【シェルスクリプト】[y/n] で処理を分岐する方法

Posted at

デフォルトでYes

sample.sh
#!/bin/bash

echo -n "実行しますか? [Y/n]: "
read ANS

case $ANS in
  "" | [Yy]* )
    # 「Yes」の場合の処理
    ;;
  * )
    # 「No」の場合の処理
    ;;
esac

デフォルトでNo

sample.sh
#!/bin/bash

echo -n "実行しますか? [y/N]: "
read ANS

case $ANS in
  [Yy]* )
    # 「Yes」の場合の処理
    ;;
  * )
    # 「No」の場合の処理
    ;;
esac

必ず入力させる

sample.sh
#!/bin/bash

function ask_yes_no {
  while true; do
    echo -n "$* [y/n]: "
    read ANS
    case $ANS in
      [Yy]*)
        return 0
        ;;  
      [Nn]*)
        return 1
        ;;
      *)
        echo "yまたはnを入力してください"
        ;;
    esac
  done
}

if ask_yes_no "実行しますか?"; then
    # 「Yes」の場合の処理
else
    # 「No」の場合の処理
fi
2
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
2
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?