shell輸入輸出重定向

給memcached添加日誌的時候用到數據流重定向,所以打算總結一下。

命令說明
command > file 將輸出重定向到 file。
command < file 將輸入重定向到 file。
command >> file 將輸出以追加的方式重定向到 file。
n > file 將文件描述符爲 n 的文件以覆蓋的方式重定向到 file。
n >> file 將文件描述符爲 n 的文件以追加的方式重定向到 file。
n >& m 將輸出文件 m 和 n 合併。
n <& m 將輸入文件 m 和 n 合併。
<< tag 將開始標記 tag 和結束標記 tag 之間的內容作爲輸入。

 

 

 

 

 

 

 

 

 

每個linux命令運行都會打開三個文件:

1、標準輸入文件(stdin):文件描述符爲0,若不重定向會默認讀取stdin文件。

2、標準輸出文件(stdout):文件描述符爲1,若不重定向會默認將輸出信息寫入stdout文件。

3、標準錯誤文件(stderr):文件描述符爲2,若不重定向會默認將錯誤信息寫入stderr文件。

 

實例

1、command > file  輸出重定向--覆蓋

[root@localhost script]# vim testOut.sh

echo "1" > out
echo "2" > out
~
~
"testOut.sh" [新] 2L, 30C 已寫入                                                                                                           
[root@localhost script]# sh testOut.sh 
[root@localhost script]# cat out
2

2、command >> file  輸出重定向--追加

[root@localhost script]# vim testOut1.sh 

echo "1" >> out1
echo "2" >> out1
~
~
"testOut1.sh" 2L, 32C 已寫入
[root@localhost script]# sh testOut1.sh 
[root@localhost script]# cat out1
1
2

3、command < file 輸入重定向

[root@localhost script]# cat out
1
2
[root@localhost script]# wc -l < out   # 將out的內容輸入給 wc -l命令作爲數據源,統計out的行數
2

 4、文件描述符n > file  

[root@localhost script]# cat test.sh
#!/bin/bash
echo "suc"
echo1 "fail"
  • 只將1輸出到out文件, 則2直接顯示在控制檯上
[root@localhost script]# sh test.sh 1>out
test.sh: line 3: echo1: command not found
[root@localhost script]# cat out
suc
  • 只將2輸出到out文件中,則1直接顯示在控制檯上
[root@localhost script]# sh test.sh 2>out
suc
[root@localhost script]# cat out
test.sh: line 3: echo1: command not found

 5、 n >& m  (m,n爲文件描述符

[root@localhost script]# cat test.sh
#!/bin/bash
echo "suc"
echo1 "fail"
[root@localhost script]# sh test.sh > out 2>&1
[root@localhost script]# cat out
suc
test.sh: line 3: echo1: command not found

6、n <& m(待補充

7、<< tag  將 tag期間的內容作爲輸入(下例的tab爲EOF)

[root@localhost script]# wc -l << EOF 
> JFDLK
> JKFLSD
> FJKSDF
> EOF
3

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章