Linux中輸入輸出重定向的問題
阿新 • • 發佈:2018-12-06
Linux 命令預設從標準輸入裝置(stdin)獲取輸入,將結果輸出到標準輸出裝置(stdout)顯示。一般情況下,標準輸入裝置就是鍵盤,標準輸出裝置就是終端,即顯示器。
輸出重定向:命令的輸出不僅可以是顯示器,還可以很容易的轉移向到檔案,這被稱為輸出重定向。
命令輸出重定向的語法為:
Here Document
Here Document 目前沒有統一的翻譯,這裡暫譯為”嵌入文件“。Here Document 是 Shell 中的一種特殊的重定向方式,它的基本的形式如下:
- $ command > file
- $ who > users
- command < file
- 標準輸入檔案(stdin):stdin的檔案描述符為0,Unix程式預設從stdin讀取資料。
- 標準輸出檔案(stdout):stdout 的檔案描述符為1,Unix程式預設向stdout輸出資料。
- 標準錯誤檔案(stderr):stderr的檔案描述符為2,Unix程式會向stderr流中寫入錯誤資訊。
- $command 2 > file
- $command 2 >> file
- $command > file 2>&1
- $command >> file 2>&1
- $command < file1 >file2
- $command &>>file
命令 | 說明 |
command > file | 將輸出重定向到 file。 |
command < file | 將輸入重定向到 file。 |
command >> file | 將輸出以追加的方式重定向到 file。 |
n > file | 將檔案描述符為 n 的檔案重定向到 file。 |
n >> file | 將檔案描述符為 n 的檔案以追加的方式重定向到 file。 |
n >& m | 將輸出檔案 m 和 n 合併。 |
n <& m | 將輸入檔案 m 和 n 合併。 |
<< tag | 將開始標記 tag 和結束標記 tag 之間的內容作為輸入。 |
- command << EOF
- document
- EOF
- 結尾的EOF 一定要頂格寫,前面不能有任何字元,後面也不能有任何字元,包括空格和 tab 縮排。
- 開始的EOF前後的空格會被忽略掉。
- #!/bin/bash
- cat << EOF
- This is a simple lookup program
- for good (and bad) restaurants
- in Cape Town.
- EOF
- #!/bin/sh
- filename=test.txt
- vi $filename <<EndOfCommands
- i
- This file was created automatically from
- a shell script
- ^[
- ZZ
- EndOfCommands
- $ command > /dev/null
- $ command > /dev/null 2>&1