Bash 脚本未记录完整输出

Bash script not recording full output

我使用下面的 Bash 脚本更新 OSX 上的软件,并在必要时重新启动。

奇怪的是,当找不到需要的软件更新时,运行 脚本的输出和日志都不包含部分输出。

例如,如果我 运行 在不需要更新的机器上执行以下操作,我将看到:

% softwareupdate -i -a
Software Update Tool
Copyright 2002-2012 Apple Inc.

Finding available software
No updates are available.

最后一行 "No updates are available" 是没有记录到我的以下脚本的日志文件中的内容:

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH 
SWLOG=/var/log/swupdate.log

(

echo "################ SoftwareUpdate Script Beginning at $(date) ################"

echo "Script Name: $(basename -- "[=12=]") "

softwareupdate -l | grep -i "restart"

if [[ $? -eq 0 ]] #reboot will be needed

    then 

        echo "Software update requiring reboot is needed"
        echo "Starting..."
        softwareupdate -i -a
        echo "################ Rebooting at $(date) ################"
        reboot

    else 

        echo "No reboot needed. Updates will be applied if needed..."
        softwareupdate -i -a    
        echo "################ SoftwareUpdate Script Ending at $(date) ################"
        echo 

fi
exit 0

) | tee -a $SWLOG

相反,日志显示:

################ SoftwareUpdate Script Beginning at Sat May 21 19:37:44 PDT 2016 ################
Script Name: swupdate.sh 
No reboot needed. Updates will be applied if needed...
Software Update Tool
Copyright 2002-2012 Apple Inc.

Finding available software
################ SoftwareUpdate Script Ending at Sat May 21 19:38:33 PDT 2016 ################

并省略了 "No updates are available."

对于为什么会发生这种情况有什么想法和建议吗?我想记录这个重要的细节。

提前致谢,丹

由于您将输出通过管道传递给 tee 命令,因此仅传递标准输出。标准错误被忽略。看起来 softwareupdate 将 "no updates available" 部分发送到标准错误。因此,将标准错误重定向到标准输出将解决您的问题。

softwareupdate -i -a  2>&1

另一种方法是使用 |&(shorthand for 2>&1 |) 而不是 | ,这会将标准错误重定向到标准输出,然后将输出通过管道传输到tee命令。

(your_commands) |& tee -a $SWLOG