| < 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.
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 > |
|