0
0
Bash Scriptingscripting~5 mins

Reading into multiple variables in Bash Scripting

Choose your learning style9 modes available
Introduction
Reading into multiple variables lets you get several pieces of information from one input line easily.
When you want to get a user's first and last name separately from one input.
When reading multiple values from a file line by line.
When you want to split a sentence into words and store them in different variables.
When you need to process command output that returns multiple values on one line.
Syntax
Bash Scripting
read var1 var2 var3 ...
Each word from the input is assigned to the variables in order.
If there are more words than variables, the last variable gets all remaining words.
Examples
Reads two words from input and stores them in firstName and lastName.
Bash Scripting
read firstName lastName
Reads three words from input and stores them in a, b, and c respectively.
Bash Scripting
read a b c
If input has more words than variables, last variable gets the rest.
Bash Scripting
read x y
# Input: hello world from bash
# x=hello, y='world from bash'
Sample Program
This script asks for your first and last name, reads them into two variables, and then greets you.
Bash Scripting
#!/bin/bash

echo "Enter your first and last name:"
read firstName lastName

echo "Hello, $firstName $lastName!"
OutputSuccess
Important Notes
If you press Enter without typing anything, variables will be empty.
You can use the -p option with read to prompt on the same line: read -p "Enter name: " first last
Use quotes around variables when using them to avoid word splitting issues.
Summary
Use read with multiple variable names to split input into parts.
The last variable gets all leftover input if there are more words than variables.
This helps handle multiple inputs easily in scripts.