Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (49.01 KB, 2 trang )
183
■ ■ ■
CHAPTER 27
Read Piped Input
M
any programs available to the UNIX or Linux operating systems have the ability to
process input from standard input through a pipe, Similarly, the following short script
demonstrates how to perform this task using a shell script. The script also demonstrates a
number of interesting techniques that are covered in more depth elsewhere in this book.
The purpose of the script is to take its input, whether from a file or stdin, and print the
data to stdout in reverse order. The script provides two ways to perform this task. The first
method works by calling the script with an argument that is the name of the file to be
reversed. Alternatively, you can pipe output from some other command into the script,
and it will then perform the reversal on its standard input.
First we initialize a counter variable that will track the lines of input the script receives.
#!/bin/sh
counter=0
Next we define the populate() function.
populate () {
counter=$(($counter+1))
eval COUNT${counter}='$LINE'
}
This function creates a new variable by calling the eval command. The eval command
performs variable and metacharacter expansion in what follows before passing the result
to the shell to evaluate; it is used here to construct a line of code (an assignment state-
ment) out of the contents of preexisting variables. This is a fairly powerful method for
creating command lines at runtime and is explained in more detail in Chapter 7.
The populate() function first increments the counter variable and then creates
a variable called COUNTnn where nn is the value of the counter that in this case refers
to the specific line of input to be reversed. The collection of these variables behaves
analogously to an array, except that the limit on the number of elements is based on the