Random Linux

Linux, video games and web hosting

If you are writing a shell script and you are needing to have a variable set by getting user input, you can do so using read. If you are needing to get a variable set, you can use read along with the variable name.

read value

Then whatever the user inputs at the prompt will be come the value for the variable “value.” This example will show you how to incorporate it into your script.

#!/bin/bash

echo “Please input a value”
read value
echo “The value that you entered is $value”

Will come out looking like this when you run it, stopping to ask the user for a value and waiting for them to input one.

# ./example
Please input a value
5
The value that you entered is 5

You could also just use read -p to pause and make the user hit a key to continue.

#!/bin/bash

read -p “Press any key to create a password”
pass=`mkpasswd -s 0 -p 12`
echo “Your new password is $pass”

Which would come out looking like this when they hit a key.

# ./example
Press any key to create a password
Your new password is 6bj8esuPE

Let us know how you use read by commenting below or adding to the conversation in our Forum Thread

April 23rd, 2011

Posted In: Uncategorized

Leave a Reply

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

*