How to Read User Input Into a Variable in Bash?


To write Bash scripts, understanding how to read user input into a variable is crucial. This involves receiving data from the user and storing it for further processing. This article will cover various methods for reading user input in Bash and include an example script for demonstration.

Reading User Input Into a Variable in Bash

Commonly used methods to read user input into a variable in Bash include:

Through prompt

Through read command

Method 1: Through Prompt

To ask the user for input and store it in a variable in Bash, you can use a prompt. The syntax for using a prompt is as follows:

read -p "Enter your website name: " <name-of-variable>

Using a prompt is beneficial when you need to ask the user for input in a specific format. Here’s an example of a Bash script that utilizes a prompt to receive user input and store it in a variable:

#!/bin/bash
read -p "Enter your Website name: " input1
read -p "Enter your Location: " input2
echo "Hello, $input1! You are from $input2

To obtain the website name and location, the read command is used twice with prompts. The variables “input1” and “input2” are then used to generate a personalized greeting with website name and display the location, here’s an example:

Method 2: Through read Command

To receive user input from the command line and store it in a variable in Bash, you can use the read command. The syntax for using the read command is as follows:

read <name-of-variable>

Using the read command is helpful when you need to prompt the user for input and store it in a variable. Here’s an example of a Bash script that demonstrates the usage of the read command to receive user input and store it in a variable:

#!/bin/bash
echo "What is your webiste name"
read input1
echo "Hello, $input1!

This code starts with the shebang `#!/bin/bash`, which specifies the interpreter to use. The `echo` command prints the message “What is your website name” on the terminal. The read command waits for user input and assigns it to the variable input1. Finally, the echo command outputs a greeting message that includes the value of input1, resulting in a personalized greeting.

Conclusion

Reading user input into a variable is crucial when writing Bash scripts. It can be done using the read command or by using a prompt. These methods allow users to obtain input from the user and store it for further processing. This article discussed the various techniques for reading user input into a variable in Bash and included example scripts to illustrate each method.

Print Friendly, PDF & Email
Categories