本文共 2719 字,大约阅读时间需要 9 分钟。
文件描符 缩写 描述
0 STDIN 标准输入
1 STDOUT 标准输出 2 STDERR 标准错误
1、重定向错误和数据
1 2 3 4 | [root@logicserver tmp]# ls -al data1 haha 2 > qingyun.txt 1 >pangfeng.txt [root@logicserver tmp]# cat qingyun;cat pangfeng.txt cat: qingyun: 没有那个文件或目录 -rw-r--r--. 1 root root 269 9 月 18 09 : 54 data1 |
2、在脚本重定向输出
2.1临时重定向
故意在脚本生成错误消息,可以将单独的一行输出重定向到STDERR,在文件描述符数字前加一个and符(&)
1 2 3 4 5 | [root@logicserver tmp]# vim data6 #!/bin/bash # echo "This is an error" >& 2 echo "This is a normal output" |
运行脚本,看不出本质区别
1 2 3 | [root@logicserver tmp]# sh data6 This is an error This is a normal output |
默认情瓿上,Linux将STDERR定向到STDOUT,但在运行脚本时重定向了STDERR,脚本中所有定向到STDERRR的文本都会被重定向
1 2 3 4 | [root@logicserver tmp]# sh data6 2 > data7 This is a normal output [root@logicserver tmp]# cat data7 This is an error |
2.2永久重定向
如果脚本有大量数据需要重定定,那重定向每个echo语名会很烦琐。用exec命令告诉 shell脚本执行期间重定向某个特定文件描述符
1 2 3 4 5 6 7 | [root@logicserver tmp]# vim data7 #!/bin/bash # exec 1 > testout echo "This is a test of redirecting all output" echo "from a scirpt to another file" echo "without having to redirect every individual line" |
1 2 3 4 5 6 | [root@logicserver tmp]# sh data7 [root@logicserver tmp]# ll test test testout test.sh [root@logicserver tmp]# cat testout This is a test of redirecting all output from a scirpt to another file |
exec命令训动一个新shell并将STDOUT文件描述符重定向到文件
1 2 3 4 5 6 7 8 9 | [root@logicserver tmp]# vim data7 #!/bin/bash # exec 2 > testerror echo "this is a error" exec 1 > testout echo "This is a test of redirecting all output" echo "from a scirpt to another file" echo "Wrong a time" >& 2 |
3、 重定向输入
exec命令允许将STDINT重定向到Linux系统上文件
exec 0< testfile 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | [root@logicserver tmp]# cat data1 the quick brown fox jumps over the lazy dog1 the quick brown fox jumps over the lazy dog2 the quick brown fox jumps over the lazy dog3 the quick brown fox jumps over the lazy dog4 the quick brown fox jumps over the lazy dog5 the quick brown fox jumps over the lazy dog6 [root@logicserver tmp]# vim data8 #!/bin/bash # exec 0 < data1 read LINE count= 1 while [ $? -eq 0 ] do echo "Line#$count:$LINE" count=$[ $count+ 1 ] read LINE done |
1 2 3 4 5 6 7 | [root@logicserver tmp]# sh data8 Line# 1 :the quick brown fox jumps over the lazy dog1 Line# 2 :the quick brown fox jumps over the lazy dog2 Line# 3 :the quick brown fox jumps over the lazy dog3 Line# 4 :the quick brown fox jumps over the lazy dog4 Line# 5 :the quick brown fox jumps over the lazy dog5 Line# 6 :the quick brown fox jumps over the lazy dog6 |
也可以这样写
1 2 3 4 5 6 7 8 9 10 | [root@logicserver tmp]# vim data8 #!/bin/bash # exec 0 < data1 count= 1 while read LINE do echo "Line#$count:$LINE" count=$[ $count+ 1 ] done |