Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Input and Output  ›  Lesson

Reading Input with read

Read user input 12 minThe read builtin waits for a line of input and stores it in one or more variables, and read -r -p is the safe everyday form.

Reading Input with read

Before backup.sh packs a 4 GB folder, it would be kind to ask: are you sure? A script can pause, wait for the user to type a line, and use the answer. The tool for that is read, built into Bash.

The rule

read -r -p asks, waits, and stores the line in your variable.

read -r -p "Back up $src? [y/n] " answer
echo "You said: $answer"
  • -p "text" prints a prompt and waits on the same line.
  • -r keeps backslashes as typed. Without it, read treats \ as an escape and silently removes it. Use -r every time unless you have a reason not to.
  • answer is where the line goes. If you give no name at all, it goes into the variable REPLY.

With several names, read splits the line on whitespace: the first word goes to the first name, the second to the second, and the last name takes everything left over. Leading and trailing spaces are trimmed.

read -r first rest     # user types:   yes please now
# first=yes   rest="please now"

Other useful options: -s hides what is typed (for passwords), -t 10 gives up after 10 seconds, and -n 1 returns after a single key. When the input ends (the user presses Ctrl-D, or a file runs out), read returns a failure status. The loops section uses that to read files line by line.

The shortcut

Every read is a three-beat pattern: prompt, name, check. Write the prompt the user sees, choose the variable, then check the value before trusting it, because people type Y, yes, or nothing at all. (The section on conditionals shows how to check it neatly.)

The user types " yes please "Step 1 of 4
  1. One name

    read -r reply trims the outer spaces and stores yes please in reply.

Drills

Answer fast — trust the rule.

quick drill

Where does read -r store the line when you give it no variable name?

quick drill

The user types one two three into read -r a b. What is in b?

quick drill

What does the -r option change?

quick drill

Which option stops a typed password from appearing on screen?

Remember

  • read -r -p "prompt " name asks, waits, and stores the line.
  • Prompt, name, check: never trust the answer unchecked.
  • Several names split the line; the last name takes the rest.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainAsk before archiving

Write the line that makes backup.sh ask Back up /home/asha/notes? [y/n] and store the answer. Explain what each option does, where the answer goes, and what happens if the user types yes please into read -r first rest.