The read
command is a fundamental tool in Bash scripting for capturing user input. It allows scripts to interact with users, gathering information dynamically during execution.
The simplest form of the read
command is:
read variable_name
This command waits for user input and stores it in the specified variable.
Here's a basic example of how to use the read
command:
echo "What's your name?"
read name
echo "Hello, $name!"
In this script, the user's input is stored in the name
variable and then used in the greeting.
The read
command can capture multiple inputs at once:
echo "Enter your first and last name:"
read first_name last_name
echo "Hello, $first_name $last_name!"
For a more compact script, you can include the prompt in the read
command:
read -p "Enter your age: " age
echo "You are $age years old."
To prevent indefinite waiting, use the -t
option to set a timeout:
read -t 5 -p "Quick! Enter a number: " number
echo "You entered: $number"
This command will wait for 5 seconds before moving on if no input is received.
read
command is sensitive to whitespace. Be cautious when parsing input with spaces.-r
option to treat backslashes literally, preventing escape character interpretation.read -s
to hide the user's typing.To further enhance your Bash scripting skills, explore these related topics:
Understanding the read
command is crucial for creating interactive Bash scripts. It provides a simple yet powerful way to gather user input, making your scripts more dynamic and user-friendly.