BASH Programming

How To Read User Input Into a Variable in Bash

When writing Bash scripts, it is essential to know how to read user input into a variable. This process involves receiving data from a user and storing it in a variable for further processing. This article will explore different methods to read user input into a variable in Bash and provide an example script that demonstrates the process.

Reading User Input Into a Variable in Bash

There are several methods to read user input into a variable in Bash, here are some commonly used methods to do it:

1: Using the read Command

The read command is used to receive user input from the command line and store it in a variable, the syntax for using the read command is as follows:

read <variable_name>

 

This method is useful when you want to prompt the user for input and store it in a variable, here is an example of a Bash script that uses the read command to receive user input and store it in a variable:

#!/bin/bash
echo "What is your name?"
read info1
echo "Hello, $info1! How old are you?"
read info2
echo "You are $info2 years old."

 

The first read command is used to receive the user’s name, and the second read command is used to receive the user’s age. The variables “info1” and “info2” are then used to print out a personalized greeting and age:

2: Using a Prompt

A prompt can be used to ask the user for input and store it in a variable, the syntax for using a prompt is as follows:

read -p "Enter your name: " <variable_name>

 

This method is useful when you want to prompt the user for input in a specific format, here is an example of a Bash script that uses a prompt to receive user input and store it in a variable:

#!/bin/bash
read -p "Enter your name: " info1
read -p "Enter your age: " info2
echo "Hello, $info1! You are $info2 years old."

 

The read command is used twice with a prompt to receive the user’s name and age, the variables “info1” and “info2” are then used to print out a personalized greeting and age:

Conclusion

Reading a user input into a variable is an essential aspect of writing Bash scripts by using the read command or a prompt, users can receive user input and store it in a variable for further processing. This article explored the different methods for reading user input into a variable in Bash and provided example scripts that demonstrate each method.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.