0
0
Bash Scriptingscripting~10 mins

Reading into multiple variables in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Reading into multiple variables
Start
Prompt user for input
Read input line
Split input by spaces
Assign parts to variables
Variables ready for use
End
The script asks for input, reads a line, splits it by spaces, and assigns each part to a variable.
Execution Sample
Bash Scripting
read var1 var2 var3
# User inputs: apple banana cherry
Reads one line of input and assigns the first word to var1, second to var2, third to var3.
Execution Table
StepInput LineVariables After ReadExplanation
1apple banana cherryvar1='apple', var2='banana', var3='cherry'Input split by spaces and assigned to variables
2Variables ready for useVariables hold the input parts for later commands
3End of reading process
💡 Input line fully read and variables assigned accordingly
Variable Tracker
VariableStartAfter ReadFinal
var1'''apple''apple'
var2'''banana''banana'
var3'''cherry''cherry'
Key Moments - 2 Insights
What happens if the user inputs fewer words than variables?
Variables without input get empty strings, as shown in execution_table row 1 where all variables get assigned only if input parts exist.
What if the user inputs more words than variables?
The last variable gets all remaining words combined, but in this example with three variables and three words, each gets one word as in execution_table row 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of var2 after step 1?
A'banana'
B'apple'
C'cherry'
D'' (empty string)
💡 Hint
Check the 'Variables After Read' column in execution_table row 1
At which step are the variables ready for use?
AStep 1
BStep 2
CStep 3
DBefore Step 1
💡 Hint
Look at the Explanation column in execution_table row 2
If the input was 'dog cat', what would var3 be after reading?
A'cat'
B'' (empty string)
C'dog cat'
D'dog'
💡 Hint
Refer to key_moments about fewer words than variables
Concept Snapshot
read var1 var2 var3
# Reads one line, splits by spaces
# Assigns first word to var1, second to var2, third to var3
# Extra words go to last variable
# Missing words leave variables empty
Full Transcript
This concept shows how to read user input into multiple variables in bash scripting. The script waits for the user to type a line, then splits that line by spaces. Each word is assigned to a variable in order. If there are fewer words than variables, the remaining variables become empty. If there are more words than variables, the last variable gets all remaining words combined. This allows scripts to capture multiple pieces of input in one command.