tail 命令用於顯示檔案的尾部內容,預設會在螢幕上列出指定檔案的最後 10 行。若一次給定多個檔案,則會在每個檔案前加上檔名標題。
tail [必要參數] [選擇參數] [檔案]
若未指定檔案或檔名為「-」,則改為讀取標準輸入。功能就是輸出檔案的末尾部分。
-n <行數>:顯示檔案末尾 k 行。
-c <位元組數>:顯示檔案末尾 k 個位元組。
-f:循環讀取(持續追蹤新增內容)。
-q:不顯示處理資訊。
-v:顯示詳細處理資訊。
先建立測試檔案 tail_text(共 12 行):
cat tail_text 01 the first line! 02 the second line! ... 12 the twelve line!
1)查看後 5 行:
tail -n 5 ./tail_text # 等價於 tail -5 tail_text
2)從第 5 行開始顯示:
tail -n +5 tail_text
3)注意 head 與 tail 的 -n 參數差異:head 的 -n 後面正負整數意義不同,而 tail 的 -n 不論正負都表示「末尾的絕對值行數」。
head -n 5 tail_text # 前 5 行 head -n -5 tail_text # 除了後 5 行外全部顯示 tail -n -5 tail_text # 仍顯示末尾 5 行
4)以位元組為單位:
tail -c 30 tail_text # 末尾 30 個位元組 head -c 30 tail_text # 開頭 30 個位元組
5)循環追蹤,即時輸出新增內容:
tail -f tail_text # 預設後 10 行 tail -f -n 12 tail_text # 自行指定行數
也可把輸出導向檔案:
tail -f tail_text > tempory
6)比較 tail 與 head 的 +/- 行為:
tail -n +5 tail_text # 從第 5 行到尾 tail -n 5 tail_text # 末尾 5 行 head -n +5 tail_text # 前 5 行 head -n 5 tail_text # 前 5 行
7)搭配管道靈活應用:
tail -n +10 tail_text | head -n -2
這個組合先從第 10 行顯示到尾,再透過 head -n -2 去掉最後兩行,藉由管道把前一個命令的結果交給後一個處理,最終只顯示第 10 行。