记录输出并同时附加到OS X的文件

时间:2017-05-20 19:46:20

标签: bash macos

我正在使用OS X,并希望记录命令的输出,同时将其附加到文件中。

我在AskUbuntu thread中发现您可以使用命令someCommand &>> someFile.txt,但这会给我一个语法错误:bash: syntax error near unexpected token '>'

如何在OS X中实现此功能?

2 个答案:

答案 0 :(得分:1)

我建议:

someCommand 2>&1 | tee -a someFile.txt

请参阅:tee‘s man page

答案 1 :(得分:0)

要开始和停止记录脚本中的所有stdout,您可以添加以下功能:

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