重定向(redirection)

Chapter 20. I/O Redirection

Table of Contents
20.1. Using exec
20.2. Redirecting Code Blocks
20.3. Applications

There are always three default files [1] open, stdin (the keyboard), stdout (the screen), and stderr (error messages output to the screen). These, and any other open files, can be redirected. Redirection simply means capturing output from a file, command, program, script, or even code block within a script (see Example 3-1 and Example 3-2) and sending it as input to another file, command, program, or script.

Each open file gets assigned a file descriptor. [2] The file descriptors for stdin, stdout, and stderr are 0, 1, and 2, respectively. For opening additional files, there remain descriptors 3 to 9. It is sometimes useful to assign one of these additional file descriptors to stdin, stdout, or stderr as a temporary duplicate link. [3] This simplifies restoration to normal after complex redirection and reshuffling (see Example 20-1).

COMMAND_OUTPUT >
# Redirect stdout to a file.
# Creates the file if not present, otherwise overwrites it.

  ls -lR > dir-tree.list
  # Creates a file containing a listing of the directory tree.

: > filename
# The > truncates file "filename" to zero length.
# If file not present, creates zero-length file (same effect as 'touch').
# The : serves as a dummy placeholder, producing no output.

filename
# The > truncates file "filename" to zero length.
# If file not present, creates zero-length file (same effect as 'touch').
# (Same result as ": >", above, but this does not work with some shells.)

COMMAND_OUTPUT >>
# Redirect stdout to a file.
# Creates the file if not present, otherwise appends to it.

  # Single-line redirection commands (affect only the line they are on):
  # --------------------------------------------------------------------

1>filename
# Redirect stdout to file "filename."
1>>filename
# Redirect and append stdout to file "filename."
2>filename
# Redirect stderr to file "filename."
2>>filename
# Redirect and append stderr to file "filename."
&>filename
# Redirect both stdout and stderr to file "filename."
# This operator is now functional, as of Bash 4, final release.

M>N
# "M" is a file descriptor, which defaults to 1, if not explicitly set.
# "N" is a filename.
# File descriptor "M" is redirect to file "N."
M>&N
# "M" is a file descriptor, which defaults to 1, if not set.
# "N" is another file descriptor.

  #==============================================================================

  # Redirecting stdout, one line at a time.
  LOGFILE=script.log

  echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE
  echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE
  echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE
  echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"."
  # These redirection commands automatically "reset" after each line.



  # Redirecting stderr, one line at a time.
  ERRORFILE=script.errors

  bad_command1 2>$ERRORFILE       #  Error message sent to $ERRORFILE.
  bad_command2 2>>$ERRORFILE      #  Error message appended to $ERRORFILE.
  bad_command3                    #  Error message echoed to stderr,
                                  #+ and does not appear in $ERRORFILE.
  # These redirection commands also automatically "reset" after each line.
  #=======================================================================

2>&1
# Redirects stderr to stdout.
# Error messages get sent to same place as standard output.
>>filename 2>&1
bad_command >>filename 2>&1
# Appends both stdout and stderr to the file "filename" ...
2>&1 | [command(s)]
bad_command 2>&1 | awk '{print $5}' # found
# Sends stderr through a pipe.
# |& was added to Bash 4 as an abbreviation for 2>&1 |.

i>&j
# Redirects file descriptor i to j.
# All output of file pointed to by i gets sent to file pointed to by j.

&j
# Redirects, by default, file descriptor 1 (stdout) to j.
# All stdout gets sent to file pointed to by j.

0< FILENAME
< FILENAME
# Accept input from a file.
# Companion command to ">", and often used in combination with it.
#
# grep search-word <filename

[j]<>filename
# Open file "filename" for reading and writing,
#+ and assign file descriptor "j" to it.
# If "filename" does not exist, create it.
# If file descriptor "j" is not specified, default to fd 0, stdin.
#
# An application of this is writing at a specified place in a file.
echo 1234567890 > File # Write string to "File".
exec 3<> File # Open "File" and assign fd 3 to it.
read -n 4 <&3 # Read only 4 characters.
echo -n . >&3 # Write a decimal point there.
exec 3>&- # Close fd 3.
cat File # ==> 1234.67890
# Random access, by golly.

|
# Pipe.
# General purpose process and command chaining tool.
# Similar to ">", but more general in effect.
# Useful for chaining commands, scripts, files, and programs together.
cat *.txt | sort | uniq > result-file
# Sorts the output of all the .txt files and deletes duplicate lines,
# finally saves results to "result-file".

Multiple instances of input and output redirection and/or pipes can be combined in a single command line.

command < input-file > output-file

Or the equivalent:

< input-file command > output-file # Although this is non-standard.

command1 | command2 | command3 > output-file

See Example 16-31 and Example A-14.

Multiple output streams may be redirected to one file.

ls -yz >> command.log 2>&1

Capture result of illegal options "yz" in file "command.log."

Because stderr is redirected to the file,

+ any error messages will also be there.

Note, however, that the following does not give the same result.

ls -yz 2>&1 >> command.log

Outputs an error message, but does not write to file.

More precisely, the command output (in this case, null)

+ writes to the file, but the error message goes only to stdout.

If redirecting both stdout and stderr,

+ the order of the commands makes a difference.

Closing File Descriptors

n<&-

Close input file descriptor n.

0<&-, <&-

Close stdin.

n>&-

Close output file descriptor n.

1>&-, >&-

Close stdout.

Child processes inherit open file descriptors. This is why pipes work. To prevent an fd from being inherited, close it.

Redirecting only stderr to a pipe.

exec 3>&1 # Save current "value" of stdout.
ls -l 2>&1 >&3 3>&- | grep bad 3>&- # Close fd 3 for 'grep' (but not 'ls').

^^^^ ^^^^

exec 3>&- # Now close it for the remainder of the script.

Thanks, S.C.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末底燎,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子明也,更是在濱河造成了極大的恐慌,老刑警劉巖幌蚊,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阐枣,死亡現(xiàn)場離奇詭異,居然都是意外死亡卷拘,警方通過查閱死者的電腦和手機(jī)仰禽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進(jìn)店門氮墨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人吐葵,你說我怎么就攤上這事规揪。” “怎么了温峭?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵猛铅,是天一觀的道長。 經(jīng)常有香客問我凤藏,道長奸忽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任清笨,我火速辦了婚禮月杉,結(jié)果婚禮上刃跛,老公的妹妹穿的比我還像新娘抠艾。我一直安慰自己,他們只是感情好桨昙,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布检号。 她就那樣靜靜地躺著腌歉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪齐苛。 梳的紋絲不亂的頭發(fā)上翘盖,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機(jī)與錄音凹蜂,去河邊找鬼馍驯。 笑死,一個(gè)胖子當(dāng)著我的面吹牛玛痊,可吹牛的內(nèi)容都是我干的汰瘫。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼擂煞,長吁一口氣:“原來是場噩夢啊……” “哼混弥!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起对省,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤蝗拿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后蒿涎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哀托,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年劳秋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了萤捆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 37,997評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡俗批,死狀恐怖俗或,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情岁忘,我是刑警寧澤辛慰,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站干像,受9級特大地震影響帅腌,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜麻汰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一速客、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧五鲫,春花似錦溺职、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽乱灵。三九已至,卻和暖如春七冲,著一層夾襖步出監(jiān)牢的瞬間痛倚,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工澜躺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蝉稳,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓掘鄙,卻偏偏與公主長得像颠区,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內(nèi)容