read

The read command in Unix-like operating systems is used in shell scripting to take input from the user or from a file. It is a simple but powerful tool for making scripts interactive or for processing input data line by line.

Basic Syntax

read [options] variable
  • variable: The name of the variable that will store the input.

  • options: Various flags that modify the behavior of the read command.

Examples

Reading User Input

echo "Enter your name:"
read name
echo "Hello, $name!"

Reading Multiple Variables

echo "Enter your first name and last name:"
read first_name last_name
echo "Hello, $first_name $last_name!"

Reading Input with a Prompt

You can use the -p option to display a prompt without using echo:

Silent Input (e.g., Passwords)

The -s option hides the input, useful for passwords:

Reading Input from a File

You can use the read command to process a file line by line:

Advanced Examples

Reading Input with a Timeout

The -t option sets a timeout for input:

Reading a Single Character

The -n option reads a specified number of characters (usually one):

Reading Input with a Delimiter

The -d option allows specifying a delimiter other than newline:

Reading an Array

Using Default Values

You can provide a default value if the user input is empty:

Practical Use Cases

Confirmation Prompt

Conclusion

The read command is a versatile and essential tool for shell scripting, enabling scripts to interact with users or process input data effectively. By understanding its various options and use cases, you can create more dynamic and responsive scripts.

Last updated