我已经编写了这个示例 bash 脚本,主要用于在远程环境中安装工具,因此我需要相当不错的日志记录。
在脚本执行期间,我想将每个步骤捕获到控制台窗口和文件中,该文件应包含有关执行的所有详细信息以及错误。
如何正确处理安装命令,目前我无法捕获文件中的输出。 在这种情况下推荐的做法是什么? 我见过使用其他变量来捕获输出的解决方案,但不知道如何在我的案例中使用它...
$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
最佳答案
嗯,您使用这个片段来执行远程任务?你可以在文件中捕获输出是正确的,但我会向你推荐远程执行框架来处理这样的事情。此类工具会妥善处理工具的输出,并将其解析后的输出提交给日志系统。
顺便说一下,如果您不运行此代码段,您将在调用“apt”时遇到权限升级问题
关于linux - 使用安装命令时如何正确重定向 bash 脚本执行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494865/