Reputation: 14299
I am using OS X and would like to log output of a command while simultaneously appending it to a file.
I found in an AskUbuntu thread that you can use the command someCommand &>> someFile.txt
but that gives me a syntax error: bash: syntax error near unexpected token '>'
How can I achieve this functionality in OS X?
Upvotes: 1
Views: 362
Reputation: 1053
To start and stop logging all of stdout in your script you can add these functions:
#####################################################################
# abort "error message"
#
# This may be called in cases where a command failure is unrecoverable
# and the program must exit. The function will write out a custom error
# message along with the return of the last command (the one that failed).
#
# usage:
#
# rm /tmp || abort "/tmp is a directory!"
#
function abort
{
local E=$?
echo "ERROR ${E}: $1"
exit ${E}
}
#####################################################################
# startLog "<log file name>"
#
# Start logging stdout to a log file as well as the terminal.
# The current stdout is saved as FD 6.
#
# usage:
#
# startLog "~/logfiles/mylog"
#
function startLog
{
local LOG="$1"
local DIR=$(dirname "${LOG}")
local TLOG=/tmp/startLog-$RANDOM
if [ ! -t 1 ]
then
echo "startLog(): logging appears to be enabled already"
return 1
else
if [ ! -d "${DIR}" ]
then
mkdir -p "${DIR}" 2>&1 ||
abort "startLog(): couldn't create ${DIR}"
fi
touch "${LOG}" || abort "startLog(): can't access ${LOG}"
mkfifo ${TLOG}
trap "rm -f ${TLOG}" EXIT
tee <${TLOG} "${LOG}" &
exec 6>&1 # save the existing stdout
exec 1>&-
exec 1>>${TLOG}
echo "startLog(): $(date)"
fi
}
#####################################################################
# stopLog "<log file name>"
#
# Stop logging stdout to both a log file and the terminal.
# Restores FD 1 from FD 6 saved by startLog()
#
# usage:
#
# stopLog
#
function stopLog
{
if [ -t 1 ]
then
echo "stopLog(): appears to be no log to stop"
return
else
echo "stopLog(): $(date)"
exec 1>&6 6>&-
fi
}
Upvotes: 0
Reputation: 88819
I suggest:
someCommand 2>&1 | tee -a someFile.txt
See: tee‘s man page
Upvotes: 1