Linux

如何在 bash 腳本日誌中添加時間戳?

  • March 16, 2022

我有一個不斷執行的腳本,我輸出到一個日誌文件:

script.sh >> /var/log/logfile

我想在附加到日誌的每一行之前添加一個時間戳。像:

Sat Sep 10 21:33:06 UTC 2011 The server has booted up.  Hmmph.

有什麼可以用的柔術嗎?

您可以通過以目前日期和時間為前綴的循環來管道腳本的輸出:

./script.sh | while IFS= read -r line; do printf '%s %s\n' "$(date)" "$line"; done >>/var/log/logfile

如果你會經常使用它,很容易創建一個 bash 函式來處理循環:

adddate() {
   while IFS= read -r line; do
       printf '%s %s\n' "$(date)" "$line";
   done
}

./thisscript.sh | adddate >>/var/log/logfile
./thatscript.sh | adddate >>/var/log/logfile
./theotherscript.sh | adddate >>/var/log/logfile

ts從 Ubuntumoreutils包中查看:

command | ts

或者,如果$command自動緩衝(需要expect-dev包):

unbuffer command | ts

引用自:https://serverfault.com/questions/310098