read in BASH

In this article, we would cover read builtin command in BASH. read builtin command is used to read from the standard input. The syntax for read is –

read [options] <var_name>

With the help of read builtin command, we can ask the user to provide input. The user’s input is stored in an variable, which is later processed as per our requirements. One of the benefits of asking for the user input and storing it in a variable is that the user wouldn’t have to provide the data multiple times. In addition to, it also makes our program efficient and contain fewer lines of code.

Next, we see how this works with the help of appropriate examples.

read in BASH

Since, it won’t be possible for us to cover all the read options. But, we discuss few of them through appropriate examples. We start with prompt option first.

Example I. -p prompt option. Use a script file – test and append the file with following lines of code.

#!/bin/bash
read -p "Enter a number: " num1
read -p "Enter second number: " num2
echo "The first number is $num1 and the second number is $num2"

To make the script executable –

chmod u+x test

And, to execute the script –

./test

Now, provide the values to display the output.

Example II. Use -s option to read the input in silent mode i.e. it won’t echo the characters typed. We continue with the above example –

#!/bin/bash
read -sp "Enter a number: " num1
read -sp "Enter second number: " num2
echo "The first number is $num1 and the second number is $num2"

Example III. Use -a option to provide input in an array.

#!/bin/bash
echo "Enter two numbers (separate them by space): "
read -a num
echo "The first number is ${num[0]} and the second number is ${num[1]}"

Example IV. If we don’t provide a variable name after read, then we need to use $REPLY

#!/bin/bash
echo "Enter a number: "
read
echo "The entered number is: $REPLY"

In conclusion, we have discussed how we can use read builtin command in BASH. If you would like to know about executing shell scripts.

Similar Posts