05. Reading User Input
Basic Syntax¶
-
Waits for user input.
-
Stores the entered value into a variable.
-
Input is read until the user presses Enter.
Example Script¶
read.sh¶
#!/bin/bash
echo -e "Hi, please type the word: \c "
read word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# 05. Reading User Input
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command read input into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
Example Execution¶
$ ./read.sh
Hi, please type the word: Linuxconfig.org
The word you entered is: Linuxconfig.org
Can you please enter two words?
Debian Linux
Here is your input: "Debian" "Linux"
How do you feel about bash scripting?
good
You said good, I'm glad to hear that!
What are your favorite colours ?
blue green black
My favorite colours are also blue, green and black:-)
Explanation¶
1. Reading Single Input¶
-
Reads one line of user input.
-
Stores it in variable
word.
Example:
2. Reading Multiple Variables¶
-
Splits input using spaces.
-
First word →
word1 -
Second word →
word2
Example:
If more words are entered, the remaining words go into the last variable.
3. Using Default Variable $REPLY¶
When no variable name is provided:
- Bash automatically stores input in
$REPLY.
Example:
4. Reading Input into an Array (-a option)¶
-
Stores space-separated values into an array.
-
Each word becomes an element.
Example:
Access elements using:
Understanding echo -e and \c¶
-
-eenables escape characters. -
\cprevents a newline, keeping the cursor on the same line for input.
Without \c, the input would appear on the next line.
Common read Options¶
| Option | Description |
|---|---|
-a |
Store input into an array |
-p |
Display prompt message |
-s |
Silent input (useful for passwords) |
-t |
Timeout for input |
-n |
Read limited number of characters |
Example with prompt:
Practical Example¶
Reading a password securely:
-shides typed characters.
Summary¶
-
readallows user interaction in Bash scripts. -
Input can be stored in variables, multiple variables, or arrays.
-
$REPLYstores input when no variable is specified. -
Options like
-a,-p, and-senhance input handling. -
Essential for creating interactive Bash programs.
The read command is a fundamental tool for building dynamic and user-driven shell scripts.