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 -pasks, 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.-rkeeps backslashes as typed. Without it,readtreats\as an escape and silently removes it. Use-revery time unless you have a reason not to.answeris where the line goes. If you give no name at all, it goes into the variableREPLY.
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.)
One name
read -r replytrims the outer spaces and storesyes pleaseinreply.
Drills
Answer fast — trust the rule.
Where does read -r store the line when you give it no variable name?
The user types one two three into read -r a b. What is in b?
What does the -r option change?
Which option stops a typed password from appearing on screen?
Remember
read -r -p "prompt " nameasks, waits, and stores the line.- Prompt, name, check: never trust the answer unchecked.
- Several names split the line; the last name takes the rest.
