Skip to the workspace
Pebellslearn by building
Input and Output  ›  Lesson

Reading Input with read

Read user input 12 minread consumes input and assigns fields to variables. Its options control backslash processing and prompting; IFS also affects splitting and trimming.

shell bash / Reading Input with read

Explore each scene at your own pace.

01 · The rule

The rule

Reading Input with read

read consumes input and assigns fields to variables. Its options control backslash processing and prompting; IFS also affects splitting and trimming.

Read a line without losing backslashes or unintended leading and trailing whitespace.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.