The read Command
read is like asking a question and waiting for someone to answer. The script stops, lets the person type a reply, and puts that reply into a labeled jar.
In this page:
Syntax
read [-p "prompt"] variable_name
The read Command
read pauses a script and waits for the user to type input, storing it into a variable. read -p "prompt" displays a prompt before waiting. It's the standard way to make an interactive script that responds to user input.
Note:
Use
read -s to read input silently, such as when prompting for a password.Example: The read Command
#!/bin/bash
echo "Simulating input via echo pipe since this runs non-interactively:"
name="Guest"
echo "Hello, $name! (in an interactive terminal, 'read -p \"Name: \" name' would prompt you)"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
-r, so backslashes in the input are treated as escapes. - Reading into a variable without quoting it later, so spaces are split.
- Expecting
readinside a pipedwhileloop to keep variables after the loop, when the pipeline runs in a subshell.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: