You are here:   Home Create a simple shell script (Part2)

dnrestcom -The simplest way to learn!

Just the simplest way to learn all the things.

Sep 24
2008

Create a simple shell script (Part2)

Posted by: dnrestcom

Tagged in: Shell , Linux , Daily

One way to create scripts that read user input is to use the command read. The read command takes a variable as an argument and stores the read input in the variable. The variable can then be used to process the user input. For example, read VARIABLE reads user input into the variable with the name VARIABLE.

The script pauses at this point, waiting for user input until Enter is pressed.

To tell the user to enter something, you need to print (echo) a line with some information, such as the following:

echo "Please enter a value for the variable :"
read VARIABLE

First, the script produces some output with echo to ask the user to enter something. Then the read command waits until the input is provided to store it in the variable VARIABLE. At the end the content, the variable is printed out with echo.

The other example is, if you want to read the user's first name and last name and then print both names to the screen, create a variable called NAME, which holds both the first and the last name: NAME=$FIRSTNAME $LASTNAME. Combine two variable and assign the combined value to another variable called NAME.

In this example, you can also see another rule of the variable handling in shell scripts. If you assign a value to a variable, you use just the name of the variable: NAME=. If you want to use the value of a variable, put a $ before the name: $FIRSTNAME.


It is often useful to assign a default value to a variable. This might prevent errors, if the user has entered a value that cannot be interpreted in a meaningful way. If the variable FIRSTNAME is empty, the default value TEST is used instead, as in the following:

NAME= $ {FIRSTNAME: = TEST}

The following is the script:

echo " Enter the first name : "
read FIRSTNAME


echo " Enter the last name : "
read LASTNAME


NAME= " $FIRSTNAME $LASTNAME "
echo "Name is $NAME"

 


Trackback(0)
Comments (0)add
You must be logged in to post a comment. Please register if you do not have an account yet.

busy

 Subscribe!

Or enter your email address:

Info