winklerrr
winklerrr

Reputation: 14717

Bash prompt with yes, no and cancel

I'm new in Bash and I'm stuck with writing a prompt function which asks the user a given questions and accepts the answers yes, no and cancel. I know that there are already a lot of answers to similar questions here on SO but I wasn't able to find an answer that fulfills all my requirements.

Requirements:

The ask function must


I came up with the following solution which doesn't work properly:

ask() {
  while true; do
    read -p "$1 [Y/n/a] " answer
    case $(echo "$answer" | tr "[A-Z]" "[a-z]") in
      y|yes|"" ) echo "true" ; return 0;;
      n|no     ) echo "false"; return 1;;
      a|abort  ) echo "abort"; exit 1;;
    esac
  done
}

# usage1
if ask "Are you happy?" >/dev/null; then
  # ...
fi

# usage2
answer=$(ask "Are you happy?")

For example, the abort does only work when I use -e but then logically the no also causes the script to halt.

Upvotes: 4

Views: 2159

Answers (1)

KamilCuk
KamilCuk

Reputation: 140880

I believe it would be just overall simpler to work the same way as read works. Remember to pick a unique name for the namereference.

ask() {
  declare -n _ask_var=$2
  local _ask_answer
  while true; do
    read -p "$1 [Y/n/a] " _ask_answer
    case "${_ask_answer,,}" in
      y|yes|"" ) _ask_var="true" ; break; ;;
      n|no     ) _ask_var="false"; break; ;;
      a|abort  ) exit 1; ;;
    esac
  done
}

ask "Are you happy?" answer
if "$answer"; then echo "Yay! Me too!"; fi

Upvotes: 5

Related Questions