[英]How to properly redirect bash script execution output when using install command
我已經編寫了這個示例 bash 腳本,我想主要用於在遠程環境中安裝工具,因此我需要相當不錯的日志記錄。
在我的腳本執行期間,我想將每個步驟捕獲到控制台 window 和應該包含有關執行的所有詳細信息以及錯誤的文件中。
如何正確處理安裝命令,目前我無法在文件中看到 output。 在這種情況下推薦的做法是什么? 我見過使用附加變量來捕獲 output 的解決方案,但不知道如何在我的情況下使用它......
$output="$(comand 2>&1)"
謝謝
#!/bin/bash
logFile="/log.log"
>$logFile
printLog(){
echo "[$(date "+%Y-%m-%d %H:%M:%S")]:" "$@" "Exit Code: $?" 2>&1 | tee -a $logFile
}
sampleFunc1(){
printLog $LINENO "sampleFunc1"
printLog $LINENO && mkdir "/dir1/dir2" && mkdir -p "/dir3/dir4" && mkdir -p "/dir5/dir6" && touch "file.txt" && cp "/file2.txt" "/dir1/dir2/"
printLog $LINENO "sampleFunc1"
printLog $LINENO ""
}
sampleFunc2(){
printLog $LINENO "sampleFunc2"
array=("/dir1/dir2" "/dir3/dir4" "/dir5/dir6")
for i in "${array[@]}"
do
if [ -d "$i" ]
then printLog $LINENO "exists $i"
else printLog $LINENO "creating $i"
mkdir -p "$i"
fi
done
printLog $LINENO "sampleFunc2"
printLog $LINENO""
}
sampleFunc3(){
printLog $LINENO "sampleFunc3"
printLog apt-get -qq install someApp
printLog $LINENO "sampleFunc3"
printLog $LINENO ""
}
sampleFunc1
sampleFunc2
sampleFunc3
嗯,您使用此代碼段執行遠程任務? 您可以在文件中捕獲 output 是對的,但我建議您使用遠程執行框架來處理此類事情。 此類工具會從工具中妥善處理 output,並可以將解析后的 output 提交給日志系統。
順便說一句,如果您不運行此代碼段,您將在權限提升方面遇到問題,在您調用“apt”的地方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.