我正在嘗試將執行的 shell 腳本的輸出發送到日志檔案。但是我想在每個輸出的行首放置一個時間戳,所以我創建了一個函式來做到這一點。但是如何將執行的 shell 腳本的結果傳遞給函式呢?
#This is a sample of the executed file testrun.sh
#!/bin/bash
echo "Script Executed."
#Actual script being run
#!/bin/bash
testlog="/home/usr/testlog.log"
log_to_file() {
echo "$(date ' %Y-%m-%d %H:%M:%S') $1" >> $testlog
}
sh /home/usr/testrun.sh >> log_to_file
如果我要正常記錄它,我會做
sh /home/usr/testrun.sh >> $testlog
但是如何將 testrun.sh 的輸出傳遞到函式 log_to_file 中,以便我可以將輸出記錄到帶有時間戳的檔案中?
uj5u.com熱心網友回復:
你當然可以做一個
log_to_file "$(sh /home/usr/testrun.sh)"
當然,如果您testrun.sh產生多行輸出,則只有第一行將時間戳作為前綴。
uj5u.com熱心網友回復:
使用while read回圈將每一行放入可以傳遞給的變數中log_to_file。
/home/usr/testrun.sh | while read -r line; do
log_to_file "$line"
done >> "$testlog"
你也可以使用ts命令而不是你的函式
/home/usr/testrun.sh | ts >> "$testlog"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468642.html
