0
0
Bash Scriptingscripting~5 mins

Prompting with read -p in Bash Scripting

Choose your learning style9 modes available
Introduction
You use read -p to ask the user a question and get their answer right away in a script.
When you want to ask the user for their name before continuing.
When you need to confirm an action like deleting a file.
When you want to get a password or secret input from the user.
When you want to choose an option from a menu.
When you want to pause and wait for the user to press Enter.
Syntax
Bash Scripting
read -p "Your question here: " variable_name
The -p option lets you show a prompt message before waiting for input.
The input typed by the user is saved in the variable you name.
Examples
This asks the user to enter their name and saves it in the variable 'name'.
Bash Scripting
read -p "Enter your name: " name
This asks for a yes or no answer and saves it in 'answer'.
Bash Scripting
read -p "Are you sure? (y/n): " answer
This shows a message and waits for the user to press Enter without saving input.
Bash Scripting
read -p "Press Enter to continue..."
Sample Program
This script asks the user for their favorite color and then shows what they typed.
Bash Scripting
#!/bin/bash
read -p "What is your favorite color? " color
echo "You chose: $color"
OutputSuccess
Important Notes
If you do not provide a variable name, the input will be saved in the default variable REPLY.
Use quotes around the prompt message to keep spaces and special characters safe.
To hide input (like passwords), use 'read -sp' instead of 'read -p'.
Summary
Use 'read -p' to ask the user a question and get their input in one step.
The input is stored in a variable you choose for later use.
It makes scripts interactive and user-friendly.