Home » Bash Read User Input

Read User Input

In this topic, we will learn how to read the user input from the terminal and the script.

To read the Bash user input, we use the built-in Bash command called read. It takes input from the user and assigns it to the variable. It reads only a single line from the Bash shell. Below is the syntax for its implementation.

Syntax

Follow the given examples to read user input from the Bash Script:

Example 1:

In this example, we read both the single and multiple variables from the Bash Script by using read command.

Program:

See the Bash Console:

Read User Input

Output:

Read User Input

What will happen if we don’t pass any variable with the read command?

If we don’t pass any variable with the read command, then we can pass a built-in variable called REPLY (should be prefixed with the $ sign) while displaying the input. It can be explained using the below program:

Program:

On Bash Console:

Read User Input

Output:

Read User Input

Example 2:

In this example, we enter the input on the same PROMPT by using the -p command line option as follows:

Program:

See the Bash Console:

Read User Input

Output:

Read User Input

Example 3:

This example is to keep the input on silent mode, such that whatever be a user input on the command line will be hidden to others.

So, we pass a username and hide the password (silent mode) by using the command line options (-s, -p) commonly as follows:

Where -s allows a user to keep the input on silent mode and -p to input on newly command prompt.

Program:

See the Bash Console:

Read User Input

Output:

Read User Input

NOTE: At the 5th line of the script, we have given a blanked line with echo command, because if we do not make it blank then, it will give output with both the password and username on the same PROMPT as the below image.

Read User Input

So, write your script by adding a blank echo command line.

Example 4: This example is to enter multiple inputs using an array. So use the -a command line option as follows:

Where -a helps script to read an array, and variable_name refers to an array.

Program:

See the code on Bash Console:

Read User Input

Output:

Read User Input


Next TopicBash Date Format

You may also like