Bash read Command - Read User Input
Using the read Command
The read command waits for the user to type a line and press Enter, and stores what was typed in a variable.
Basic Usage
Example: Ask for a Name
Save this as name.sh:
#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name!"
Run it:
./name.sh
What is your name?
Liam
Hello, Liam!
In the output above, "Liam" is what the user typed.
The Try it Yourself editor has no keyboard input, so its examples send the input to the script with echo.
Show a Prompt (-p)
Use -p to show a prompt on the same line as the input:
Example: Prompt on the Same Line
Save this as age.sh:
#!/bin/bash
read -p "Enter your age: " age
echo "You are $age years old."
Run it:
./age.sh
Enter your age: 25
You are 25 years old.
Read Several Values
Give read several variable names. The input is split on spaces, one word per variable. The last variable gets the rest of the line:
Example: First and Last Name
Save this as fullname.sh:
#!/bin/bash
read -p "First and last name: " first last
echo "First: $first"
echo "Last: $last"
Run it:
./fullname.sh
First and last name: Emma Watson
First: Emma
Last: Watson
Hide the Input (-s)
Use -s to hide what the user types, for example for passwords:
Example: Hidden Input
Save this as secret.sh:
#!/bin/bash
read -s -p "Password: " pass
echo
echo "Your password has ${#pass} characters."
Run it:
./secret.sh
Password:
Your password has 8 characters.
Read a File Line by Line
Use read in a while loop to go through a file one line at a time. The -r option keeps backslashes as they are, and IFS= keeps spaces at the start of lines:
Example: Read names.txt
Save this as lines.sh:
#!/bin/bash
while IFS= read -r line; do
echo "Name: $line"
done < names.txt
Run it:
./lines.sh
Name: Liam
Name: Emma
Name: Noah
Options Overview
-p "text": Show a prompt-s: Do not show what is typed-r: Keep backslashes as normal characters-t 5: Stop waiting after 5 seconds-n 1: Stop after 1 character, without waiting for Enter