read prompts in bash script

Last Updated on: August 16, 2020

We’ve previously taken a quick look at the builtin read command, where we use the built-in read to populate the $REPLY variable, which holds the value of read when a variable is not supplied to read, it would store whatever you type in the stdin, and we then echo it.

In this guide, we would use the read to produce a prompt, and a way to supply read a variable.

Fire up your console and type the following command:

					

read -p "What is Your Name: " name

The syntax is using a read with the -p option, and you include the string that appear in the prompt. The last argument (name) is the variable we want to populate, so whatever input the user type is stored in this variable.

This is the output of the above command, go ahead and type in a string or your name:

					

user@server:~/bin$ read -p "What is Your Name: " name
What is Your Name: Mr. Devsrealmer

Now, the variable name has the value you typed in memory, you can echo it as follows:

					

user@server:~/bin$ echo "You typed $name"
You typed Mr. Devsrealmer

Cool right! You can turn the whole thing into a simple script:

					

#!/bin/bash
read -p "What is Your Name? " name
echo "Your Name is $name"
exit 0

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

Your email address will not be published. Required fields are marked *