« Back to Shell scripting

Prompt for user input in a shell script

Shell scripts can be powerful for automation. Sometimes, we want to ask the user for input. Let’s have a look at a few options that can be very handy for your next shell script!

Fill a variable with input provided by the user

If we like the user to provide us with some details, like a name, email address, or hostname, we can use the read command.

read -p "What is your name? " name
echo "Your name is: ${name}"

How does it work? The read -p asks for user input and stores the result in the variable $name. On the second line we use this to display the value provided.

Prompt for a Yes/No answer

while true; do
    read -p "Do you want to continue? " yesno
    case $yesno in
        [Yy]*)
            echo "You entered Yes!"
            # Insert here a task to do
            break
        ;;
        [Nn]*)
            # Exit the program, as user answered "No"
            exit
        ;;
        *)
            echo "Please answer Yes (y) or No (n)."
        ;;
    esac
done

So how does this work?

Step 1: Wait

The while true makes the program go into a loop.

Step 2: Ask for user input and process it

As there is a read -p directly after the loop, it will wait for user input and put the result in the variable $yesno. If that is a Y (or y), it will perform the step related to that. The asterix behind the [Yy] allows the user to input Yes, or Yup, or Yeah, as long as it starts with a small or capital Y.

Step 3: Perform the action

After the choice has been made, the action will be performed. If we answer N/n/No/no/Nope/NOK/etc, the program will stop as there is an exit command. In case the answer was something with a Y/y, then we first will perform the action, followed by a break. This break stops the while true loop, otherwise we get stuck into that.

Feedback

Small picture of Michael Boelen

This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution.

Mastodon icon