所谓代码块,就是由多条语句组成的一个整体;for、while、until 循环,或者 if...else、case...in 选择结构,或者由{ }包围的命令都可以称为代码块。
请转到《Shell 组命令》了解更多关于{}的细节。
将重定向命令放在代码块的结尾处,就可以对代码块中的所有命令实施重定向。
【实例 1】使用 while 循环不断读取 nums.txt 中的数字,计算它们的总和。
1. #!/bin/bash
2.
3. sum=0
4. while read n; do
5. ((sum += n))
6. done <nums.txt #输入重定向
7. echo "sum=$sum"
将代码保存到 test.sh 并运行:
[linuxyz.cn]$ cat nums.txt
80
33
129
71
100
222
8
[linuxyz.cn]$ . ./test.sh
sum=643
对上面的代码进行改进,记录 while 的读取过程,并将输出结果重定向到 log.txt 文件:
1. #!/bin/bash
2.
3. sum=0
4. while read n; do
5. ((sum += n))
6. echo "this number: $n"
7. done <nums.txt >log.txt #同时使用输入输出重定向
8. echo "sum=$sum"
将代码保存到 test.sh 并运行:
[linuxyz.cn]$ . ./test.sh
sum=643
[linuxyz.cn]$ cat log.txt
this number: 80
this number: 33
this number: 129
this number: 71
this number: 100
this number: 222
this number: 8
【实例 2】对{}包围的代码使用重定向。
1. #!/bin/bash
2.
3. {
4. echo "Linux学习指南";
5. echo "http://linuxyz.cn";
6. echo "7"
7. } >log.txt #输出重定向
8.
9. {
10. read name;
11. read url;
12. read age
13. } <log.txt #输入重定向
14.
15. echo "$name 已经$age 岁了,它的网址是 $url"
将代码保存到 test.sh 并运行:
[linuxyz.cn]$ . ./test.sh
Linux学习指南已经 7 岁了,它的网址是 http://linuxyz.cn
[linuxyz.cn]$ cat log.txt
Linux学习指南
http://linuxyz.cn
7