Bash Script – Read User Input

14 Feb, 2022
In this article, we’ll discuss how to read user input in BASH.
We can simply get user input from the read command in BASH. It provides a lot of options and arguments along with it for more flexible usage, but we’ll cover them in the next few sections. For now, let’s see how a basic read command can be used.
#!usr/bin/env bash

read name

echo "Hello, $name"
So, in the above script, the “#!/usr/bin/env bash” is the shebang operator that indicates the interpreter to run the script in the BASH environment. We have used the read command to get the user input in the variable name. The echo command is an optional command to just verify that we have stored the input in the name variable. We use $ in front of the variable command so as to fetch and parse the literal value of the variable. 
Read command provides a lot of arguments that can be passed to it so as to get the user input in a flexible way. Some of the few arguments are discussed here:
Prompt String (-p)
Password Input (-s)
Changing the Delimiter (IFS)
Parsing to the array (-a)
Limiting Length of the Input (-n)
Timed Input (-t)
Using this argument, we can prompt a string before the input. This allows the user to get the idea of what to input without using echo before the read command. Let us take a look at the demonstration of the argument of prompting a string to the read command.
#!usr/bin/env bash

read -p "Enter your name : " name

echo "Hello, $name"
  
From the demonstration, we can see that there was a string prompt before the input from the user because we have used the “-p” argument before the input variable, which gives one more argument the string before the variable. This allows a better interface and readability of the program. We can say that this kind of built-in echo functionality is in the read command with the string prompt.  
Now assume that we want to type in the password in the input and how insecure it would be to display while the user is typing. Well, we have the solution for that. We can use the -s argument to silent the echo from the user input. This allows working with the read command in a secure way. 
#!usr/bin/env bash

read -sp "Enter your password : " pswd

echo -e "\nYour password is $pswd"
In the above demonstration, the input is silenced i.e. the interface doesn’t print what the user is typing. But we can see that I typed 12345 and is stored and retrieved later from the variable. You can notice that we have nested the arguments -s and -p as -sp to use both the arguments together. Also, the echo command is modified as we use the -e argument to use formatted strings i.e use “\n” and other special characters in the string.
Using this argument we can change the way we assign the variables the value i.e. if we want to get the multiple inputs using single read command we can do that using space-separated values.
#!usr/bin/env bash

read -p "Enter name age and country : " name age country

echo "Name : $name"
echo "Age : $age"
echo "Country : $country"
From the above example, we can see that it cleverly assigned the variables to the values provided. You can see that the last variable had 3 spaces so since it was the last input, it assigned itself everything but if it was not the last input, it could mess up the format. 
If we had provided four inputs then the word “United” would have been the country variable and the rest of the stuff in the last variable. We got a bit understanding of delimiters here, delimiters are the patterns or characters that are used to distinguish different sets of entities in our case the input variables. We can change the delimiters, by default we have space as the delimiters in the read command. Let’s look at how we can achieve that.
#!usr/bin/env bash

IFS="," read -p "Enter name, age, city and country : " name age city country

echo "Name : $name"
echo "Age : $age"
echo "City : $city"
echo "Country : $country"
In the following example, we have used the IFS or the Internal Field Separator. We have set the IFS as “,” at the beginning of the read command. As you can see this doesn’t count the space as the separator in the variable assignment. This leads to proper and formatted inputs as desired, you can choose IFS as the character that is not used in the inputs internally otherwise it can disorient the format as expected. We can use IFS as “.“, “,“, “/“, “\“. “;“, etc. as this is not used commonly in the input and it also depends on the goal you are trying to achieve.
We can parse the input directly to an array at once. We can specify the -a argument to do the same. This creates an element and assigns the array elements the input value. Let’s see the demonstration.
#!usr/bin/env bash

read -a array -p "Enter the elements of array : " 
for n in ${array[*]};
do 
    echo "$n"
done
In this example, we are inputting the values to the array variable which is a list/array. The name can be anything relevant to your program. The delimiter here is as said space by default, you can use the IFS argument at the beginning of the read command to format the input as said in the above section. But here for the demonstration, I have kept it default to space. We can add the argument –a to append the input to an array provided just after that. We can verify that the read command worked and stored all the elements by iterating over the array.
We can use the range-based for loops for simplicity and print the value of each element in the array. We can use the “{}” to identify the variable and [*] indicating all the elements in the array, we have the iterator as “n” which we print the value after every iteration. Hence in the output, we were able to get all the elements of the array. We can even use “[@]” instead of “[*]” as it would iterate over the array in a little different way but serve the same purpose.
We can even limit the length of input in the read command. If we want the user to restrict the user with certain limitations on the input we can do this using the -n argument.
#!usr/bin/env bash

read -n 6 -p "Enter the name : " name
echo -e "\nName : $name"
In the above demonstration, we can see that even if I don’t hit Carriage Return/ Enter / Newline, the command stops after entering the 6th character in the input. Thus this can be used in limiting the user with some sensitive inputs like username, password, etc.  We enter the argument -n followed by the number of characters we want to limit to.
This is done to input from the user in a time-constrained way. We can specify the argument as -t and the number of seconds we want to wait till exiting from the input prompt. 
#!usr/bin/env bash

read -p "Enter the name : " -t 8 name
echo -e "\nName : $name"
Thus, we can see that the prompt waited for 8 seconds but we didn’t press Enter and hence it returned with no input to the further instructions in the script if any. We can pass in the -t argument to set the timeout followed by the number of seconds to wait for the user to input the required value.
rkbhola5
Bash-Script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting