Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 輸入輸出重定向完整解析:Here Document 與 /dev/null

Unix 命令預設從標準輸入(stdin)讀資料、把結果送到標準輸出(stdout)。一般情況下 stdin 就是鍵盤,stdout 就是螢幕。而重定向,就是把這兩端接到檔案或其他地方去。

輸出重定向

command > file

例如把登入者清單寫進檔案,螢幕上就不會有任何輸出:

who > users
cat users

注意 > 是覆寫,原內容會被清掉:

echo line 1 > users
cat users
line 1

想接在檔案末尾,改用 >>:

echo line 2 >> users
cat users
line 1
line 2

輸入重定向

command < file

原本等著鍵盤輸入的指令,改成從檔案讀:

wc -l users      # 輸出 2 users
wc -l < users    # 只輸出 2

差別在於前者知道檔名所以會一併印出,後者只知道自己在讀標準輸入。記法很簡單:> 是輸出,< 是輸入。

三個標準串流

  • 標準輸入 stdin,檔案描述符 0
  • 標準輸出 stdout,檔案描述符 1
  • 標準錯誤 stderr,檔案描述符 2

因此 command > file 等同 command 1> file。要單獨處理錯誤輸出:

command 2 > file
command 2 >> file

要把正常與錯誤輸出合併到同一個檔案:

command > file 2>&1
command >> file 2>&1

同時重定向 stdin 與 stdout:

command < file1 > file2

常用重定向寫法速查

  • command > file:輸出覆寫到 file。
  • command < file:輸入來自 file。
  • command >> file:輸出追加到 file。
  • n > file / n >> file:把描述符 n 覆寫/追加到 file。
  • n >& m:輸出合併;n <& m:輸入合併。
  • << tag:把 tag 標記之間的內容當作輸入。

Here Document

Here Document 暫譯為「嵌入文檔」,形式如下:

command << delimiter
document
delimiter

它把兩個 delimiter 之間的內容當成輸入交給 command。兩個容易出錯的細節:

  • 結尾的 delimiter 必須頂格,前面不能有任何字元,後面也不能有空白或 tab。
  • 開始的 delimiter 前後空白會被忽略。

計算嵌入內容的行數:

wc -l << EOF
This is a simple lookup program for good (and bad) restaurants in Cape Town.
EOF
3

寫在腳本裡也很常見:

#!/bin/bash
cat << EOF
This is a simple lookup program for good (and bad) restaurants in Cape Town.
EOF

甚至可以用來自動化 vi 編輯:

#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from a shell script
^[
ZZ
EndOfCommands

執行後 cat test.txt 就會看到那一行內容(會伴隨 Vim: Warning: Input is not from a terminal 的提示,屬正常現象)。實務上更推薦用 cat > file << 'EOF',加上引號可避免變數被提前展開。

/dev/null 這個黑洞

想執行指令但不想看到任何輸出,就把它丟進 /dev/null:

command > /dev/null

寫入這個檔案的內容會被直接丟棄,讀它也讀不到任何東西。若連錯誤訊息也要一起屏蔽:

command > /dev/null 2>&1

在 crontab 或 systemd 服務裡,這個寫法能避免無用的郵件通知與日誌噪音;相對地,若反而想保留錯誤、只丟掉正常輸出,可寫 command 1> /dev/null。

Copyright © Linux教程網 All Rights Reserved