Bash Script - Read User Input
Last Updated :
12 Dec, 2023
Interacting with users is a crucial aspect of many Bash scripts. Whether prompting for information, selecting options, or confirming actions, reading user input is essential for building powerful and flexible scripts. This guide provides a comprehensive overview of reading user input in Bash, covering essential concepts, advanced techniques, and best practices.
Basic User Input
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 arguments
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)
Prompt String
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 -sp "Enter your password : " pswd
echo -e "\nYour password is $pswd"

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.
Password Input
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 it 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.
Changing the Delimiter
Using this argument we can change the way we assign the variables the value i.e. if we want to get multiple inputs using a 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.
Parsing to an Array
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.
Limiting Length of the Input
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.
Timed Input
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.
Conclusion
In this article we discussed how to get input from users in Bash scripts. The basic method is using the "read" command. We explored different ways to enhance this, such as adding a prompt using "-p," hiding passwords with "-s," changing delimiters, and limiting input length with "-n." We also saw how to parse input into arrays with "-a" and set a time limit for input using "-t." These techniques make Bash scripts more interactive and user-friendly, allowing developers to create efficient command-line tools.
Similar Reads
Batch Script - Input / Output In this article, we are going to learn how to take input from users using Batch Script. Taking User Input:@echo off echo Batch Script to take input. set /p input= Type any input echo Input is: %input% pauseExplanation :The first 'echo' command is used to print a string.In the next line, 'set /p' com
1 min read
Bash Script - Features These days, there are various shell writing options available out there, and each one of them has its own unique features. Just as it does, Bash Shell contains some of the best features that make it more productive and usable. For each project, there are specific requirements for the features, and t
3 min read
How to take user input in JavaScript? Interacting with users is the best way to create engaging and dynamic web applications. Taking user input allows your applications to be interactive and responsive. Here we will see the approach to take user input in JavaScript, specifically using the prompt method, which is perfect for beginners.Ap
3 min read
How To Run Bash Script In Linux? Bash scripts, also called shell scripts, are programs that help automate tasks by storing a series of commands that often go together, like updates or upgrades. These scripts make it easier to perform tasks automatically instead of typing each command manually. After creating a Bash script, you can
6 min read
Shell Scripting - Readonly Command In this tutorial, we will learn about the âreadonlyâ command. Using the readonly command, you can assign a particular value to a variable that can neither be changed nor modified by subsequent assignments nor be unset. Syntax:readonly name[=value] readonly [-aAf] [name[=value] Most used options: -p
3 min read
Bash Scripting - While Loop A while loop is a statement that iterates over a block of code till the condition specified is evaluated to false. We can use this statement or loop in our program when do not know how many times the condition is going to evaluate to true before evaluating to false. Â Table of Content The Syntax of
15+ min read
Bash Scripting - Case Statement A case statement in bash scripts is used when a decision has to be made against multiple choices. In other words, it is useful when an expression has the possibility to have multiple values. This methodology can be seen as a replacement for multiple if-statements in a script. Case statements have an
8 min read
How to Get User Input in Ruby? The input of users is a very vital part of many programs which allows customization and interaction. In Ruby, there are various methods to get input from the user, each having its own benefits and use cases. This article will discuss two different ways to obtain user input in Ruby. Table of Content
2 min read
Shell Script to Read Data From a File File reading is quite an important task in a Programmer's life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming
3 min read
Bash Scripting - Split String In this article, we will discuss how to split strings in a bash script. Dividing a single string into multiple strings is called string splitting. Many programming languages have a built-in function to perform string splitting but there is no built-in function in bash to do so. There are various met
4 min read