5

【笨問題】命令列執行結果同時輸出到螢幕跟檔案

 2 years ago
source link: https://blog.darkthread.net/blog/tee/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【笨問題】命令列執行結果同時輸出到螢幕跟檔案

calendar.svg 2022-05-10 09:25 PM comment.svg 1 eye.svg 2,635

CLI 指令執行結果要存成檔案很簡單,加上 > filename 將 stdout 轉向檔案就可以了。(或是 2>&1 >filename 連錯誤訊息也一併寫入)

但這麼做有個缺點,導向檔案後螢幕完全看不到結果,遇到耗時較久的作業會無法掌握進度,連程式有沒有當掉都搞不清楚。

有沒有辦法同時將結果輸出到螢幕跟檔案呢?

很簡單,但我最近才學會 - Unix 世界有個 tee 指令 專門滿足這個需求。

tee 在 Unix 為內建指令,在 Windows 可使用 Cmder 或安裝 Git for Windows,而 PowerShell 也有對映的 Tee-Object 提供相同功能。

以下示範 dir | tee output.txt,螢幕可看到目錄內容,並同時存入 output.txt,就這麼簡單!

Fig1_637877860024199363.png

在中文版 Windows 使用時可能會遇到中文編碼問題(如下圖),由於 tee 會以 UTF-8 顯示,若命令列視窗為 Big5 (Code Page 950) 編碼中文會變亂碼,此時執行 chcp 65001 切換 Code Page 為 UTF-8 即可。

Fig2_637877860025067581.png

順便試試 PowerSheel Tee-Object:

Fig3_637877860025961762.png

and has 1 comment

Comments

Post a comment

Comment
Name Captcha 35 - 13 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK