In Linux, the read command is used to read data from standard input (usually the keyboard) and assign the input data to a variable. This command is very useful in scripts as it allows the script to pause execution and wait for user input.
Basic Usage
read variable
This will wait for the user to input a line of text, and after the user presses the enter key, the input text (excluding the newline character) will be assigned to the variable variable
.
Options
-p "prompt"
: Prints a prompt message before waiting for input.
read -p "Please enter your name: " name
This will display the prompt message “Please enter your name: “, and then wait for user input.
-n N
: Reads a specified number of characters instead of a whole line.
read -n 1 -p "Press any key: " key
This will only read one character and prompt “Press any key: “.
-s
: Reads input in silent mode, the input will not be displayed on the screen.
read -s -p "Enter your password: " password
This will be used to read passwords, where the entered password will not be displayed on the terminal.
-a array
: Reads input into an array.
read -a words
echo \\${words[@]}
This will read a line of text and split it into words, storing them in the array words
.
-d delim
: Specifies a delimiter instead of the default newline character.
read -d ':' -p "Enter your name: " name
echo $name
This will read input until the colon (:) is reached.
Practical Examples
Reading a single variable:
read -p "Enter your name: " name
echo "Hello, $name!"
Reading multiple variables:
read -p "Enter your name and age: " name age
echo "Name: $name, Age: $age"
Reading a line and splitting:
read -p "Enter a list of numbers: " -a numbers
for num in "\${numbers[@]}"; do echo $num
done
This will read a line of numbers and split them into the array numbers
, then iterate through the array to print each number.
Reading until a specific delimiter:
read -d ',' -p "Enter a comma-separated list: " list
echo $list
This will read input until the comma (,) is reached.
Reading a character:
read -n 1 -p "Press a key: " key
echo "You pressed: $key"
The read command is a powerful tool for interacting with users, allowing flexible reading and processing of user input data as needed.

Want to know more?
Quickly scan the code to follow