前言
輸入/輸出重新導向是 shell 用來處理標準輸入(standard input)、標準輸出(standard output)與標準錯誤(standard error)的重要功能。它可將指令執行的輸出導向到檔案中,也可以將執行程式或指令所需的引數或輸入由檔案導入,其應用範圍可說相當廣範。
本文將介紹其基本的觀念。










在HP-UX上每一個unix 的process預設來說都有60個file descriptors (從0到59)。

一般說來,前三個file descriptor在process開始執行時就會被啟動: file descriptor 0就是standard input (stdin標準輸入),file descriptor 1 為 standard output (stdout標準輸出) ,而 file descriptor 2 則為 standard error output(stderr標準錯誤輸出)。對於一個UNIX程式來說, 它會從”標準輸入”做讀取 (如:鍵盤) 而將輸出寫到”標準輸出”(如:螢幕)。以下我們要來看如何在UNIX Shell中對

這三個標準的file descriptor做導向和管理。









1.Standard input/output redirection

 
























語法說明
cmd < file將stdin導向至file
cmd > file將stdout導向至file
cmd >> file將stdout導向至file並且將輸出內容附加在檔案之後
cmd 2> error.log將stderr導向至error.log
cmd &將指令在背景執行
cmd 2>&1 &指令在背景執行,並將stderr導向至stdout


利用重新導向我們可將原本的標準輸出及輸入導向至其它的地方。


例如:


將指令date的標準輸出導向至檔案/tmp/datelog。

#date > /tmp/datelog


將指令mail的標準輸入來源指定為/etc/hosts。

#mail mary@hputain.taiwan.hp.com < /etc/hosts


將指令tar的標準錯誤輸出導向至檔案/tmp/tar.err。

#tar cvf /dev/rmt/0m /home 2> /tmp/tar.err

# cat /tmp/tar.err

tar: cannot open /dev/rmt/0m











2. pipeline and tee

利用pipeline ‘|’ 我們可以將一個指令的的輸出導向為下另一個指令的輸入。


例如:


#du –sk /home/* | sort –rn

 


透過’|’將指令du的輸出結果導向為指令sort的輸入來源,其結果就相當於下列二行指令的效果:


#du –sk /home/* > dulog
#sort –rn < dulog


通常當第一個指令的標準輸出透過pipeline重新導向成第二個指令的輸入時,得到的結果是第二個指令的輸出,我們無法看到中間第一個指令的輸出結果。
但是利用tee這個指令,可以從標準輸入讀取後,將輸出導向至標準輸出及所指定的檔案。

#du –sk /home/* | tee /tmp/du-unsort | sort -rn
2408 /home/hcc
312 /home/ftp
296 /home/cynthia
40 /home/eng
32 /home/hpems
#cat /tmp/du-unsort
296 /home/cynthia
40 /home/eng
312 /home/ftp
2408 /home/hcc
32 /home/hpems


arrow
arrow
    全站熱搜

    噗噗噗的潛水珽 發表在 痞客邦 留言(0) 人氣()