🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Read Input

The read command takes one line typed at the keyboard and stores it in a variable. The script can then use that typed value like any other value.

Read one line into a variable

The read line waits for a typed line and stores it in name. With Ada typed, the echo greets that stored value.

read name
echo "Hello $name"

Show a prompt with -p

The -p option prints a prompt before reading the line. With Ada typed, the greeting below is the line the script prints.

read -p "Name: " name
echo "Hello $name"

Read two words into two variables

One line can fill two variables at once. With Ada Lovelace typed, the first word fills first and the second fills last.

read first last
echo "First: $first"
echo "Last: $last"

Example

read -p "City: " city
read -p "Country: " country
echo "You live in $city, $country"

Key points

  • The read command stores one typed line into a named variable.
  • Reading stops when the person presses Enter at the end of the line.
  • The option -p prints a prompt before the line is read.
  • One read command can fill two variables from two words on one line.
  • The first word fills the first variable and the second word fills the second.
  • A value from read works with echo and $ exactly like an assigned value.

In this example, the first read shows a City prompt and stores the typed line Paris in city. The second read shows a Country prompt and stores France in country. The echo line joins both stored values into one sentence. That sentence is the line the script prints.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command reads one typed line into a variable named city?