Shell 輸入/輸出重定向
阿新 • • 發佈:2018-10-31
技術分享 輸入 spa 文件 標準輸入 文件描述 錯誤 roc 傳遞
stdin輸入可以從鍵盤,也可以從文件得到
stout命令執行完成,把成功結果輸出到屏幕,默認是屏幕
stderr命令執行有錯誤,把錯誤也輸出到屏幕上面,默認也是屏幕
文件描述符
標準輸入stdin:對應的文件描述符是0,符號是<和<<,/dev/stdin -> /proc/self/fd/0
標準輸出stdout:對應的文件描述符是1,符號是>和>>,/dev/stdout -> /proc/self/fd/1
標準錯誤stderr:對應的文件描述符是2,符號是2>和2>>,/dev/stderr -> /proc/self/fd/2
輸出重定向實例
#默認情況下,stdout和stderr默認輸出到屏幕 [root@st ~]# ls ks.cfg wrongfile ls: cannot access wrongfile: No such file or directory ks.cfg
#標準輸出重定向到stdout.txt文件中,錯誤輸出默認到屏幕。1>與>等價 [root@st ~]# ls ks.cfg wrongfile >stdout.txt ls: cannot access wrongfile: No such file or directory [root@st ~]# cat stdout.txt ks.cfg
#標準輸出重定向到stdout.txt,錯誤輸出到err.txt。也可以使用追加>>模式。 [root@st ~]# ls ks.cfg wrongfile >stdout.txt 2>err.txt [root@st ~]# cat stdout.txt err.txt ks.cfg ls: cannot access wrongfile: No such file or directory
#將錯誤輸出關閉,輸出到null。同樣也可以將stdout重定向到null或關閉 # &1代表標準輸出,&2代表標準錯誤,&-代表關閉與它綁定的描述符
[root@st ~]# ls ks.cfg wrongfile 2>&- ks.cfg [root@st ~]# ls ks.cfg wrongfile 2>/dev/null ks.cfg
#將錯誤輸出傳遞給stdout,然後stdout重定向給xx.txt,也可以重定向給null。
#順序為stderr的內容先到xx.txt,stdout後到。 [root@st ~]# ls ks.cfg wrongfile >xx.txt 2>&1
[root@st ~]# cat xx.txt
ls: wrongfile: No such file or directory
ks.cfg
#將stdout和stderr重定向到null [root@st ~]# ls ks.cfg wrongfile &>/dev/null
輸入重定向
#從stdin(鍵盤)獲取數據,然後輸出到catfile文件,按Ctrl+d結束 [root@st ~]# cat >catfile this is catfile [root@st ~]# cat catfile this is catfile
#輸入特定字符eof,自動結束stdin [root@st ~]# cat >catfile <<eof > this > is > catfile > eof [root@st ~]# cat catfile this is catfile
Shell 輸入/輸出重定向