文件的描述符和重定向
文件描述符是和文件的輸入、輸出相關聯的非負整數,Linux內核(kernel)利用文件描述符(file descriptor)來訪問文件。打開現存文件或新建文件時,內核會返回一個文件描述符。讀寫文件也需要使用文件描述符來指定待讀寫的文件。常見的文件描述符是stdin、stdout和stderr。
系統預留文件描述符
- 0 —— stdin(標準輸入)
- 1 —— stdout(標準輸出)
- 2 —— stderr(標準錯誤)
重定向將輸入文本通過截取模式保存到文件:
echo "this is a text line one" > test.txt
寫入到文件之前,文件內容首先會被清空。
重定向將輸入文本通過追加模式保存到文件:
echo "this is a text line one" >> test.txt
寫入到文件之後,會追加到文件結尾。
標準錯誤輸出:
[root@localhost text]# cat linuxde.net
cat: linuxde.net: No such file or directory
標準錯誤輸出的重定向方法:
方法一:
[root@localhost text]# cat linuxde.net 2> out.txt //沒有任何錯誤提示,正常運行。
方法二:
[root@localhost text]# cat linuxde.net &> out.txt
因爲錯誤信息被保存到了out.txt文件中。
[root@localhost text]# cat linuxde.net 2> /dev/null
將錯誤輸出丟棄到/dev/null
中,/dev/null是一個特殊的設備文件,這個文件接受到任何數據都會被丟系,通常被稱爲位桶、黑洞。
tee命令
tee命令可以將數據重定向到文件,另一方面還可以提供一份重定向數據的副本作爲後續命令的stdin。
在終端打印stdout同時重定向到文件中:
ls | tee out.txt
1.sh
1.txt
2.txt
eee.tst
EEE.tst
one
out.txt
string2
www.pdf
WWW.pdf
WWW.pef
[root@localhost text]# ls | tee out.txt | cat -n
1 1.sh
2 1.txt
3 2.txt
4 eee.tst
5 EEE.tst
6 one
7 out.txt
8 string2
9 www.pdf
10 WWW.pdf
11 WWW.pef
重定向腳本內的文本片段(多行文本)
#!/bin/bash
cat <<EOF>text.log
this is a text line1
this is a text line2
this is a text line3
EOF
在cat <<EOF>text.log
與下一個EOF
行之間的所有文本都會當作stdin數據輸入到text.log中。
自定義文件描述符
除了0、1和2分別是stdin、stdout和stderr的系統預留描述符,我們還可以使用exec命令
創建自定義文件描述符,文件的的打開模式有只讀模式、截斷模式和追加模式。
< 操作符用於從文件中讀取至stdin:
echo this is a test line > input.txt
exec 3<input.txt //自定義文件描述符3打開並讀取文件
在命令中使用文件描述符3:
cat <&3
this is a test line
這裏需要注意只能讀取一次,如果再次使用需要重新創建文件描述符。
> 操作符用於截斷模式的文件寫入(數據在文件內容被截斷之後寫入):
exec 4>output.txt
echo this is a new line >&4
cat output.txt
this is a new line
>> 操作符用於追加模式的文件寫入(添加數據到文件中,原有數據不會丟失):
exec 5>>output.txt
echo this is a appended line >&5
cat output.txt
this is a new line
this is a appended lin
有數據不會丟失):**
```bash
exec 5>>output.txt
echo this is a appended line >&5
cat output.txt
this is a new line
this is a appended lin