DistributedNetworks DistributedNetworks


Unix Shell Scripts   «Prev  Next»
Lesson 6 A command to read keyboard input
Objective Use the read command to collect user input.

Command to Read Keyboard Input

The read command is used to allow a user to interact with a shell script, typing a response to a question or other prompt that you include as part of your shell script. The information that the user enters is assigned to a variable so that it can be used within your script.
Later in the course, you will learn in detail how to use variables, but here are two basic rules about variables that you create yourself:
  1. You can name a variable anything you want. Try to use descriptive names. All uppercase names are normally used to make them easy to see in your scripts. An example is INPUT or RESPONSE.
  2. When the name of a variable is used with a dollar sign in front of it, such as $INPUT or $RESPONSE, the value contained in the variable is referred to. This is true no matter how the variable was assigned.

The read command uses one parameter: the variable that the user’s entry should be stored in. For example, if you need to ask the user for the name of a file to work with, you could use these lines in your script:

echo Enter the name of the file to download:
read DOWNLOADFILE

The user sees the following text onscreen when the script runs:
Enter the name of the file to download: 

with the cursor waiting at the beginning of the next line for the user to enter a filename.
Once the user types something and presses Enter, the text is placed in the DOWNLOADFILE variable , which can be used in your shell script as needed. A simple example of using the variable value is to repeat back to the user what they entered, as verification (note the dollar sign, as described above):

echo The name of the file you entered was 
$DOWNLOADFILE.

When this line is executed, the user sees something like this (depending on what was entered):
The name of the file you entered was 
cruise_update.html.
Once the variable contains the text entered by the user, that information can be manipulated or tested in many ways, as you will learn about in future modules.

Read keyboard Input command - Exercise

Click on the Exercise link below to practice what you have learned in the UNIX Lab.
Read keyboard Input command - Exercise
Click on the following link to read about using unix unix and the read command.
Using - unix - read - command
The next lesson shows you how to prepare a script file for execution