0
0
Bash Scriptingscripting~5 mins

read command in Bash Scripting

Choose your learning style9 modes available
Introduction
The read command lets your script wait for the user to type something. It saves what the user types into a variable so your script can use it later.
When you want to ask the user for their name and use it in your script.
When you need to get a password or secret input from the user.
When you want to pause the script until the user presses Enter.
When you want to get multiple pieces of information from the user in one line.
When you want to read input from a file or another command.
Syntax
Bash Scripting
read [options] variable_name
The read command waits for the user to type and press Enter.
The typed text is stored in the variable you name after read.
Examples
Waits for user input and saves it in the variable 'name'.
Bash Scripting
read name
Shows a prompt message before waiting for input.
Bash Scripting
read -p "Enter your age: " age
Reads input silently (no echo) for passwords.
Bash Scripting
read -s password
Reads two words separated by space into var1 and var2.
Bash Scripting
read var1 var2
Sample Program
This script asks the user for their favorite color, waits for input, and then shows what they typed.
Bash Scripting
#!/bin/bash

echo "What is your favorite color?"
read color
echo "You chose: $color"
OutputSuccess
Important Notes
If the user types multiple words, only the first word goes into the variable unless you use multiple variables.
Use the -p option to show a prompt on the same line as the input.
Use the -s option to hide input, useful for passwords.
Summary
The read command gets input from the user and saves it in a variable.
You can prompt the user and control how input is read with options.
It helps make scripts interactive and user-friendly.