文件描符??????縮寫??????????????????描述
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 |
?
本文轉自 zouqingyun 51CTO博客,原文鏈接:http://blog.51cto.com/zouqingyun/1697088,如需轉載請自行聯系原作者