stdin,stdout,stderr
stdin=0
stdout=1
stderr=2
使用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那樣從文件中讀取數據:
$ cmd < file
2. 重定向腳本內部的文本塊
可以將腳本中的文本重定向到文件。要想將一條警告信息添加到自動生成的文件頂部,可以
使用下面的代碼:
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文件的內容顯示如下:
3. 自定義文件描述符
文件描述符是一種用於訪問文件的抽象指示器(abstract indicator)。存取文件離不開被稱為
“文件描述符”的特殊數字。 0 、 1 和 2 分別是 stdin 、 stdout 和 stderr 預留的描述符編號。
exec 命令創建全新的文件描述符。如果你熟悉其他編程語言中的文件操作,那么應該對文
件打開模式也不陌生。常用的打開模式有3種。
- 只讀模式。
- 追加寫入模式。
- 截斷寫入模式。
< 操作符可以將文件讀入 stdin 。 > 操作符用於截斷模式的文件寫入(數據在目標文件內容被
截斷之后寫入)。 >> 操作符用於追加模式的文件寫入(數據被追加到文件的現有內容之后,而且
該目標文件中原有的內容不會丟失)。文件描述符可以用以上3種模式中的任意一種來創建。
創建一個用於讀取文件的文件描述符
[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 )來從另一個文件中讀取或是重新讀取上一個文件。
創建一個用於寫入(截斷模式)的文件描述符:
[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
追加模式
[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
