1. 程式人生 > >shell學習整理(5)-玩轉檔案描述符及重定向

shell學習整理(5)-玩轉檔案描述符及重定向

常見的檔案描述符: 標準輸入stdin, 標準輸出stdout, 標準錯誤stderr


1. 將輸出的文字重定向或者儲存到一個檔案中
$ echo "this is a sample" > temp.txt   通過這條命令會將"this is a sample"寫入到temp.txt檔案裡,注意如果沒有這個檔案會建立這個檔案,如果已經有temp.txt了,會清空原來的內容,重新輸入。


2. 將文字追加到目標檔案後面
$ echo "this is a sample" >>temp.txt


3. 檢視檔案內容
$ cat aaaa.txt
"this is a samplae"
"this is a samplae"


4. 當命令輸出錯誤資訊時, stderr 資訊就會被打印出來
$ cat aaaa.txt
cat: aaaa.txt: No such file or directory


5. 檔案重定向
[email protected]
MINGW64 ~
$ echo "b1" >b1


[email protected] MINGW64 ~
$ echo "b2">b2


[email protected] MINGW64 ~
$ echo "b3">b3


[email protected] MINGW64 ~
$ echo b1 > b1


[email protected] MINGW64 ~
$ cp b1 b2; cp b2 b3


[email protected] MINGW64 ~
$ chmod 000 a1


A[email protected]
MINGW64 ~
$ cat b1
b1


[email protected] MINGW64 ~
$ cat b2
b1


[email protected] MINGW64 ~
$ cat b3
b1


6. 但是有一個方法既可以將資料重定向到檔案,還可以提供一份重定向資料的副本作為後續命令的 stdin 。這一切都可以使用 tee 來實現。舉個例子:要在終端中列印stdout ,同時將它重定向到一個檔案中,那麼可以這樣使用 tee 


[email protected] MINGW64 ~
$ cat b1 | tee out.txt | cat -n
     1  b1


[email protected]
MINGW64 ~
$ cat b1 | tee out.txt | cat -n
     1  b1


[email protected] MINGW64 ~
$ cat out.txt
b1


7. 使用stdin做為命令韓引數,只需要將-做為命令的檔名引數即可
$ echo who is this | tee -
who is this


8. >和>>是有區別的,兩者都可以將文字重定向導檔案,前者先清空檔案,然後再寫入內容,後者會將內容追加到現有檔案的尾部。即前者是清空並寫入,後者是加入到文字尾部。