Unix 命令默認(rèn)從標(biāo)準(zhǔn)輸入設(shè)備(stdin)獲取輸入,將結(jié)果輸出到標(biāo)準(zhǔn)輸出設(shè)備(stdout)顯示。一般情況下,標(biāo)準(zhǔn)輸入設(shè)備就是鍵盤,標(biāo)準(zhǔn)輸出設(shè)備就是終端,即顯示器。
命令的輸出不僅可以是顯示器,還可以很容易的轉(zhuǎn)移向到文件,這被稱為輸出重定向。
命令輸出重定向的語法為:
$ command > file
這樣,輸出到顯示器的內(nèi)容就可以被重定向到文件。
例如,下面的命令在顯示器上不會(huì)看到任何輸出:
$ who > users
打開 users 文件,可以看到下面的內(nèi)容:
$ cat users
oko tty01 Sep 12 07:30
ai tty15 Sep 12 13:32
ruth tty21 Sep 12 10:10
pat tty24 Sep 12 13:07
steve tty25 Sep 12 13:03
$
輸出重定向會(huì)覆蓋文件內(nèi)容,請(qǐng)看下面的例子:
$ echo line 1 > users
$ cat users
line 1
$
如果不希望文件內(nèi)容被覆蓋,可以使用 >> 追加到文件末尾,例如:
$ echo line 2 >> users
$ cat users
line 1
line 2
$
和輸出重定向一樣,Unix 命令也可以從文件獲取輸入,語法為:
command < file
這樣,本來需要從鍵盤獲取輸入的命令會(huì)轉(zhuǎn)移到文件讀取內(nèi)容。
注意:輸出重定向是大于號(hào)(>),輸入重定向是小于號(hào)(<)。
例如,計(jì)算 users 文件中的行數(shù),可以使用下面的命令:
$ wc -l users
2 users
$
也可以將輸入重定向到 users 文件:
$ wc -l < users
2
$
注意:上面兩個(gè)例子的結(jié)果不同:第一個(gè)例子,會(huì)輸出文件名;第二個(gè)不會(huì),因?yàn)樗鼉H僅知道從標(biāo)準(zhǔn)輸入讀取內(nèi)容。
一般情況下,每個(gè) Unix/Linux 命令運(yùn)行時(shí)都會(huì)打開三個(gè)文件:
默認(rèn)情況下,command > file 將 stdout 重定向到 file,command < file 將 stdin 重定向到 file。
如果希望 stderr 重定向到 file,可以這樣寫:
$command 2 > file
如果希望 stderr 追加到 file 文件末尾,可以這樣寫:
$command 2 >> file
2 表示標(biāo)準(zhǔn)錯(cuò)誤文件(stderr)。
如果希望將 stdout 和 stderr 合并后重定向到 file,可以這樣寫:
$command > file 2>&1
或
$command >> file 2>&1
如果希望對(duì) stdin 和 stdout 都重定向,可以這樣寫:
$command < file1 >file2
command 命令將 stdin 重定向到 file1,將 stdout 重定向到 file2。
全部可用的重定向命令列表
| 命令 | 說明 |
|---|---|
| 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 | 將開始標(biāo)記 tag 和結(jié)束標(biāo)記 tag 之間的內(nèi)容作為輸入。 |
Here Document 目前沒有統(tǒng)一的翻譯,這里暫譯為”嵌入文檔“。Here Document 是 Shell 中的一種特殊的重定向方式,它的基本的形式如下:
command << delimiter
document
delimiter
它的作用是將兩個(gè) delimiter 之間的內(nèi)容(document) 作為輸入傳遞給 command。
注意:
下面的例子,通過 wc -l 命令計(jì)算 document 的行數(shù):
$wc -l << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF
3
$
也可以 將 Here Document 用在腳本中,例如:
#!/bin/bash
cat << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF
運(yùn)行結(jié)果:
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
下面的腳本通過 vi 編輯器將 document 保存到 test.txt 文件:
#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands
運(yùn)行腳本:
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
打開 test.txt,可以看到下面的內(nèi)容:
$ cat test.txt
This file was created automatically from
a shell script
$
如果希望執(zhí)行某個(gè)命令,但又不希望在屏幕上顯示輸出結(jié)果,那么可以將輸出重定向到 /dev/null:
$ command > /dev/null
/dev/null 是一個(gè)特殊的文件,寫入到它的內(nèi)容都會(huì)被丟棄;如果嘗試從該文件讀取內(nèi)容,那么什么也讀不到。但是 /dev/null 文件非常有用,將命令的輸出重定向到它,會(huì)起到”禁止輸出“的效果。
如果希望屏蔽 stdout 和 stderr,可以這樣寫:
$ command > /dev/null 2>&1文件