在shell脚本中可以通过在done命令的末尾添加处理命令,使用管道或者重定向循环输出结果
$ cat test.sh
#!/bin/bash
for i in 1 2 3 4 5 6
do
echo "i=$i"
done > output.txt
echo "this is outside loop"
$ ./test.sh
this is outside loop
$ cat output.txt
i=1
i=2
i=3
i=4
i=5
i=6
本例中将for循环的输出重定向到output.txt文件。同样可以将循环的输出通过管道传送给其他命令,不仅仅是for循环,对于其它循环同样适用。
$ cat test.sh
#!/bin/bash
for i in 1 2 3 4 5 6
do
echo "i=$i"
done | grep "4"
echo "this is outside loop"
$ ./test.sh
i=4
this is outside loop
本例中将循环的输出通过管道交由grep命令处理。