在shell脚本中,可以对循环的输出使用管道或进行重定向。这可以通过在done命令之后添加一个处理命令来实现:
for file in /home/rich/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
echo "$file is a file"
fi
done > output.txt
shell会将for命令的结果重定向至文件output.txt,而不再显示在屏幕上。
考虑下面这个将for命令的输出重定向至文件的例子:
$ cat test23
#!/bin/bash
# redirecting the for output to a file
for (( a = 1; a < 10; a++ ))
do
echo "The number is $a"
done > test23.txt
echo "The command is finished."
$ ./test23
The command is finished.
$ cat test23.txt
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
shell创建了文件test23.txt并将for命令的输出重定向至该文件。for命令结束之后,shell一如往常地显示了echo语句。
这种方法同样适用于将循环的结果传输到另一个命令:
$ cat test24
#!/bin/bash
# piping a loop to another command
for state in "North Dakota" Connecticut Illinois Alabama Tennessee
do
echo "$state is the next place to go"
done | sort
echo "This completes our travels"
$ ./test24
Alabama is the next place to go
Connecticut is the next place to go
Illinois is the next place to go
North Dakota is the next place to go
Tennessee is the next place to go
This completes our travels
for命令的输出通过管道传给了sort命令,由后者对输出结果进行排序。运行该脚本,可以看出结果已经按state的值排好序了。