1

I have the following script that continuously accepts input from the user until he/she enters some form of y* or Y*.

while true; do
read -p "Are you ready? " yn
case $yn in
    [Yy]* ) break;;
    [Nn]* ) ;;
    * ) echo "Please answer yes or no.";;
esac
done

However, I would like to break out of the while loop when the user simply presses enter. I tried using \n, \r, and \r\n but these don't seem to be the right patterns.

I am using Cygwin if that makes a difference (though I would also like to know the answer for a Linux distribution like Ubuntu).

1 Answer 1

4

Because read strips the newline, you'll have to match an empty string, "":

#!/bin/bash
while true; do
    read -p "Are you ready? " yn
    case "$yn" in
        [Yy]*|"") break;;
        [Nn]*) ;;
        *) echo "Please answer yes or no.";;
    esac
done

Depending on your application logic, you can (obviously) make that a separate case branch, like: "") break;;.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.