Getting User Input

Problem

You need to get input from the user.

Solution

Use the read statement:

read

or:

read -p "answer me this " ANSWER

or:

read PRE MID POST

Discussion

In its simplest form, a read statement with no arguments will read user input and place it into the shell variable REPLY.

If you want bash8 to print a prompt string before reading the input, use the -p option. The next word following the -p will be the prompt, but quoting allows you to supply multiple words for a prompt. Remember to end the prompt with punctuation and/or a blank, as the cursor will wait for input right at the end of the prompt string.

If you supply multiple variable names on the read statement, then the read will parse the input into words, assigning them in order. If the user enters fewer words, the extra variables will be set blank. If the user enters more words than there are variables on the read statement, then all of the extra words will be part of the last variable in the list.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.