HowtoForge

The Linux read Command

The read command in Bash reads a line from the standard input and splits it into fields.

Linux read Command Examples

The read command in Linux is a built-in command used in shell scripts and command lines to read a line of input from the standard input (stdin) and assign it to a variable. Here are some examples of how to use the read command:

Basic Usage:

read varname
echo "You entered: $varname"

This script waits for the user to enter some text, which is then stored in the variable varname. When the user presses Enter, the script displays the entered text.

Reading Multiple Values:

echo "Enter two values:"
read var1 var2
echo "You entered: $var1 and $var2"

This allows the user to enter two separate values, which are stored in var1 and var2. The values should be separated by space.

Silent Input (Useful for Passwords):

read -s -p "Enter your password: " password
echo
echo "Password entered."

The -s option makes read silent, meaning it does not echo the input back to the terminal. This is useful for sensitive information like passwords. The -p option allows you to display a prompt.

Reading a Whole Line Including Spaces:

IFS= read -r line
echo "You entered: $line"

By setting IFS (Internal Field Separator) to an empty value and using -r (to prevent backslash escapes from being interpreted), the entire line of input, including spaces, is read into the variable line.

Setting a Timeout:

read -t 5 -p "Enter your name (you have 5 seconds): " name
echo "Hello, $name"

The -t option sets a timeout. In this example, read will wait for 5 seconds for the user to enter their name.

Reading from a File:

while IFS= read -r line
do
  echo "Line: $line"
done < filename.txt

This script reads lines from a file named filename.txt one by one.

Commandline Options of the read command

Here are some of its commonly used options:

The read command is a powerful tool in Bash scripting for handling user inputs and parsing text. You can combine these options as needed to fit your specific requirements.

The Linux read Command