More small fry Unix commands

Unix Insider |  Operating Systems

Last month I started a series on Unix's smaller but no less useful commands. This month we continue the series.


The read command is not actually a separate program in the Korn shell. It is
built into the Korn shell. Its purpose is to allow input information to be
read from standard input (usually the keyboard). In order to try out read,
type ksh and press Enter.

Type the following command, and then enter a single word with no spaces as in
the example below. The command read x causes input to be read from standard input
and assigned to the variable $x, which is then echoed to the screen.

$ read x; echo $x

read is usually used in shell scripts to accept user input and assign it to a
variable. The following example, simpmenu, is a two-pick menu that uses read
to accept the user's input.

A menu is displayed at lines 7 through 18. At line 19 the user selection is
accepted into the variable x and then one of two possible actions is executed
at lines 20 through 23 and 25 through 28. This action is repeated until the
user enters the number 9 as a menu pick. This is controlled at line 5. If $x is not
equal (-ne) to 9 at line 5 then the loop continues to execute.

Note the additional reads at lines 22 and 27. These reads seem to have no
variable named for the input. The read command supplies a default variable
named REPLY. That is used if no variable is named with the read command. I am
only using read at lines 22 and 27 to give the user the opportunity to see
the last page of output before the screen is cleared.

 1   # simpmenu
 2   # a simple menu program
 4   x=1
 5   while [ $x -ne 9 ]
 6   do
 7       clear
 8       echo
 9       echo
10       echo "Enter your selection"
11       echo
12       echo
13       echo "1  Display directory"
14       echo "2  Display processes"
15       echo
16       echo
17       echo "9  Exit"
19       read x
20       if [ $x -eq 1 ]
21       then
22           ls -l|more ; echo "Press Enter" ; read
23       fi
25       if [ $x -eq 2 ]
26       then
27           ps -ef|more ; echo "Press Enter" ; read
28       fi
29   done

Using the default REPLY variable, the first exercise could be shortened to:

Join us:






Answers - Powered by ITworld

Ask a Question