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 -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.