Skip to content
AgileLogics
4 min read

Reading Input

Prerequisites: Script arguments

read reads a line of input into a variable — from the keyboard, or from a file or pipe.

Asking the user

# illustrative
read -r -p "What's your name? " name
echo "Nice to meet you, $name!"
What's your name? Ada
Nice to meet you, Ada!
  • -p shows a prompt.
  • -r keeps backslashes as typed — always use it.
  • -s hides what's typed (for passwords); -t 10 gives up after 10 seconds.

Reading from other input

read reads from standard input, so it works with pipes, files, and here-strings (<<<), which pass a single string as input:

read -r first last <<< "Ada Lovelace"
echo "First: $first"
echo "Last: $last"

IFS=, read -r city country <<< "Lima,Peru"
echo "$city is in $country"
First: Ada
Last: Lovelace
Lima is in Peru
  • With several variable names, read splits the line on spaces; the last variable gets the rest of the line.
  • IFS=, changes the separator to a comma for that one read.

Confirming a dangerous action

# illustrative
read -r -p "Delete all logs? [y/N] " answer
if [[ $answer == [yY] ]]; then
  rm -f logs/*.log
  echo "Deleted."
else
  echo "Cancelled."
fi

Defaulting to "no" (the capital N) means pressing Enter by accident is safe.

Prefer arguments for automation

Interactive prompts block scripts that run unattended (from cron or CI). Accept arguments or environment variables first, and only prompt when they're missing and a person is at the keyboard.