Getting Input from the User

 < Day Day Up > 



As was previously mentioned, variables will often get their values from user input. We need some method to take the data that the user types in at the keyboard and put it into the variables in our script. The vehicle for accomplishing this is the read statement. The read statement takes whatever is typed in, up to the point of the user pressing the Enter key, and puts that value into the designated variable. The following is an example of the syntax:

  somevariable=   read somevariable

Let’s examine a script that has the user enter data and uses the echo statement to print the data to the screen. Type the following into your favorite text editor and save it as scriptsix.sh:

  #!/bin/bash   lastname=smith   firstname=john   echo Please type in your first name   read firstname   echo Please type in your last name   read lastname   echo   echo Hello $firstname $lastname it is good to meet you.   exit 0

When you run this script you should see something similar to what is shown in Figure 20.11, although your display will vary, of course, depending on the name you enter.

click to expand
Figure 20.11: Getting user input.

You see this is a rather friendly script! It also demonstrates how to create a variable and how to fill that variable with data the user provides. Notice that when we display the values of the variables to the screen, we get the values the user typed in, not the initial values we put in our script. The contents of the variables were overwritten by the data the user entered. If you will recall, we stated earlier that they are called variables because their content can vary.



 < Day Day Up > 



Moving From Windows to Linux
Moving From Windows To Linux (Charles River Media Networking/Security)
ISBN: 1584502800
EAN: 2147483647
Year: 2004
Pages: 247
Authors: Chuck Easttom

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net