shell基礎知識之 stdin,stdout,stderr和文件描述符

stdin,stdout,stderr

stdin=0
stdout=1
stderr=2node

使用tee來傳遞內容,把stdout 做爲stdin 傳到下個命令編程

root@172-18-21-195:/tmp/pratice# echo "who is this" | tee -  # -至關於傳入到stdout,因此打印2次
who is this
who is this
root@172-18-21-195:/tmp/pratice# echo "who is this" | tee - | cat -n  # cat -n 是顯示行數
     1  who is this
     2  who is this

把stderr給導入指定地方編程語言

root@172-18-21-195:/tmp/pratice# ls asdf out.txt 2>/dev/null  1>/dev/null  
root@172-18-21-195:/tmp/pratice# ls asdf out.txt &>out.txt  # 能夠簡寫成這樣,也能夠寫成2>&1 這樣,二選一
root@172-18-21-195:/tmp/pratice# cat out.txt
ls: cannot access asdf: No such file or directory
out.txt
1. 將文件重定向到命令

藉助小於號(<),咱們能夠像使用stdin那樣從文件中讀取數據:this

$ cmd < file
2. 重定向腳本內部的文本塊

能夠將腳本中的文本重定向到文件。要想將一條警告信息添加到自動生成的文件頂部,能夠
使用下面的代碼:code

root@172-18-21-195:/tmp/pratice# cat << EOF >log.txt
> this is a test for log.txt
> EOF
root@172-18-21-195:/tmp/pratice# cat log.txt
this is a test for log.txt

出如今cat < log.txt與下一個EOF行之間的全部文本行都會被看成stdin數據。
log.txt文件的內容顯示以下:
dns

3. 自定義文件描述符

文件描述符是一種用於訪問文件的抽象指示器(abstract indicator)。存取文件離不開被稱爲
「文件描述符」的特殊數字。 0 、 1 和 2 分別是 stdin 、 stdout 和 stderr 預留的描述符編號。
exec 命令建立全新的文件描述符。若是你熟悉其餘編程語言中的文件操做,那麼應該對文
件打開模式也不陌生。經常使用的打開模式有3種。內存

  1. 只讀模式。
  2. 追加寫入模式。
  3. 截斷寫入模式。
    < 操做符能夠將文件讀入 stdin 。 > 操做符用於截斷模式的文件寫入(數據在目標文件內容被
    截斷以後寫入)。 >> 操做符用於追加模式的文件寫入(數據被追加到文件的現有內容以後,並且
    該目標文件中原有的內容不會丟失)。文件描述符能夠用以上3種模式中的任意一種來建立。

建立一個用於讀取文件的文件描述符input

[root@dns-node2 tmp]# cat input.txt
aaa
bbb
ccc

[root@dns-node2 tmp]# exec 3<input.txt  # 建立一個新的描述符3, 3和<和input.txt之間千萬不能有空格,必須緊挨着。
[root@dns-node2 tmp]# cat <&3
aaa
bbb
ccc

若是要再次讀取,咱們就不能繼續使用文件描述符 3 了,而是須要用 exec 從新建立一個新的
文件描述符(能夠是 4 )來從另外一個文件中讀取或是從新讀取上一個文件。
建立一個用於寫入(截斷模式)的文件描述符:cmd

[root@dns-node2 tmp]# exec 4>output.txt
[root@dns-node2 tmp]# echo newline >&4  # &在這裏能夠理解爲獲取4這個FD的內存地址(我的理解,該理解來自go語言)
[root@dns-node2 tmp]# cat output.txt
newline

追加模式test

[root@dns-node2 tmp]# exec 5>>input.txt
[root@dns-node2 tmp]# echo Append line >&5
[root@dns-node2 tmp]# cat input.txt
aaa
bbb
ccc
Append line
相關文章
相關標籤/搜索