大多數 UNIX 系統命令從你的終端接受輸入并將所產生的輸出發送回??到您的終端,一個命令通常從一個叫標準輸入的地方讀取輸入,默認情況下,這恰好是你的終端,同樣,一個命令通常將其輸出寫入到標準輸出,默認情況下,這也是你的終端,
輸出重定向
有兩種方式
- [root@localhost ~]# command1 > file1 會覆寫檔案原來內容
- [root@localhost ~]# command1 >> file2 不會覆寫檔案原來內容,追加到檔案末尾
[root@localhost ~]# cat /etc/passwd | grep "root" > test.sh [root@localhost ~]# cat /etc/passwd | grep "root" >> test.sh
輸入重定向
和輸出重定向一樣,Unix 命令也可以從檔案獲取輸入,這樣,本來需要從鍵盤獲取輸入的命令會轉移到檔案讀取內容,
語法:[root@localhost ~]# command1 < file1
注意:輸出重定向是大于號(>),輸入重定向是小于號(<),
[root@localhost ~]# wc -l /etc/passwd [root@localhost ~]# wc -l < /etc/passwd [root@localhost ~]# grep "root" < /etc/passwd
注意:上面三個例子的結果不同:第一個例子,會輸出檔案名;后二個不會,因為它僅僅知道從標準輸入讀取內容,
同時替換輸入和輸出
語法:[root@localhost ~]# command1 < infile > outfile
執行command1,從檔案infile讀取內容,然后將輸出寫入到outfile中,
[root@localhost ~]# wc -l </etc/passwd >test
重定向深入講解
一般情況下,每個 Unix/Linux 命令運行時都會打開三個檔案:
- 標準輸入檔案(stdin): stdin的檔案描述符為0,Unix程式默認從stdin讀取資料,
- 標準輸出檔案(stdout):stdout 的檔案描述符為1,Unix程式默認向stdout輸出資料,
- 標準錯誤輸出檔案(stderr):stderr的檔案描述符為2,Unix程式會向stderr流中寫入錯誤資訊,
默認情況下,command > file 將 stdout 重定向到 file,command < file 將stdin 重定向到 file,
# 將 stderr 重定向到 file 檔案 [root@localhost ~]# command 2 > file # 將 stderr 追加到 file 檔案末尾 [root@localhost ~]# command 2 >> file # 將 stdout 和 stderr 合并后重定向到 file 檔案 [root@localhost ~]# command > file 2>&1 [root@localhost ~]# command >> file 2>&1 # 將 stdin 和 stdout 都重定向,command 命令將 stdin 重定向到 file1,將 stdout 重定向到 file2, [root@localhost ~]# command < file1 > file2
/dev/null 檔案
/dev/null 是一個特殊的檔案,寫入到它的內容都會被丟棄;如果嘗試從該檔案讀取內容,那么什么也讀不到,但是 /dev/null 檔案非常有用,將命令的輸出重定向到它,會起到"禁止輸出"的效果,
# 如果希望執行某個命令,但又不希望在螢屏上顯示輸出結果,那么可以將輸出重定向到 /dev/null: [root@localhost ~]# command > /dev/null # 如果希望屏蔽 stdout 和 stderr,可以這樣寫: [root@localhost ~]# command > /dev/null 2>&1
https://www.runoob.com/linux/linux-shell-io-redirections.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/155256.html
標籤:Linux
