Dan Dan - 6 months ago 21
Bash Question

Bash script not recording full output

I use the Bash script below to update software on OSX, and reboot when necessary.

Oddly enough, neither the output of running the script nor the log contain part of the output when no software update needed is found.

For example, if I run the following on a machine that needs no updates, I'll see:

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

Finding available software
No updates are available.


The last line "No updates are available" is what is not getting recorded to my log file of the following script:

#!/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 -- "$0") "

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


Instead, the log shows:

################ 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 ################


And omits the "No updates are available."

Any ideas, suggestions why this might be happening? I'd like to record this important detail.

Thanks in advance, Dan

Answer

Since you are piping the output to the tee command, only the standard output is passed. The standard error gets ignored. Looks like softwareupdate sends the "no updates available" part to the standard error. So redirecting the standard error to standard output will get rid of your problem.

softwareupdate -i -a  2>&1

Another way is to use |&(shorthand for 2>&1 |) instead of | , this redirects standard error to standard output and then pipes the output to the tee command.

(your_commands) |& tee -a $SWLOG