Using read in a Bash Script

Last Updated on: 

We previously looked at using echo with options in a shell, in this guide we would combine it with read command to prompt for user input.

Create and open up a new text file: nano $HOME/bin/hw3.sh

Add the following:

					

#!/bin/bash
echo -n "Hello There, may I ask your name: "
read
echo "Hello $REPLY"
exit 0

Let’s understand the command line by line:

#!/bin/bash  – This is the interpreter, nothing new here

read – This reads a line from the standard input (e.g your keyboard input), you are to pass a variable to the read command. If you do not, it is going to use the default internet variable, which is the $REPLY variable.

echo “Hello $REPLY” – The $REPLY  is the default value when a variable is not supplied to read, it would store whatever you type in the stdin, and we then echo it.

Remember to add an execution bit to the file: chmod +x $HOME/bin/hw3.sh

This the output:

					

user@server:~/bin$ hw3.sh
Hello There, may I ask your name: ? Mr. Devsrealmer
Hello Mr. Devsrealmer
user@server:~/bin$

In future guide, we would talk more on the read builtin command

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 *

css.php