天天看點

shell 重定向

輸入重定向

預設的輸入檔案是标注輸入stdin 0,

可以使用下面的方法重定向輸入:

command < filename

這樣就會從filename檔案中讀取資料送給command指令使用.

例如 cat /etc/passwd

輸出重定向

預設的輸出檔案是标準輸出stdout 1,

可以使用下面的方法重定向輸出:

command > filename

這樣就能把command的結果輸出到filename檔案中.

例如 ls > /tmp/output.txt

錯誤重定向

預設的标準錯誤輸入到stderr 2,

可以使用下面的方法重定向錯誤:

command 2> filename

例如 find / -iname “*.conf” 2>fileerrors.txt

注: 建立一個新檔案的方法:

> newfile.name

丢棄資訊

command >/dev/null

丢棄輸出資訊

command 2>/dev/null

丢棄錯誤資訊

command &>/dev/null

同時丢棄輸出資訊和錯誤資訊

例如:

grep vivek /etc/passwd >/dev/null && echo “Vivek found” || “Vivek not

found”

here document

herre document告訴shell去從目前的由特定字元串包含起來的字元串中讀取内容.文法如下:

command <<HERE
text1
text2
testN
$varName
HERE
           

這裡的HERE可以換成其他任何字元.

例子:

wc -w <<EOF

This is a test.

Apple juice.

100% fruit juice and no added sugar, colour or preservative.

EOF

結果: 16