Bash:捕获FD std(out / err)并注入函数

时间:2011-02-25 12:59:22

标签: bash exec pipe

我想创建一个通用函数来捕获脚本的输出并将它们插入到日志中。 caputre将从文件的开头开始。日志具有以下格式:[tag] [time]:text。 我已经制作了这段代码(基于bash高级脚本指南

lib文件

batch_init

function batch_init {
    here=$(dirname $0)
    . ${here}/../etc/batch.conf
    scriptName=$1
    batch_exec_uid=$$
    fifoFile="${tmp_dir}${scriptName}.${batch_exec_uid}.fifo"
    curTime="$(date +%H%M%S)"
    logFileName="$(basename ${scriptName}).${curTime}.${batch_exec_uid}.log"
}

batch_log

function batch_log {
    level="info"
    OPTIND=1

    read content

    while getopts :x:y: OPTION
    do
      case $OPTION in
       x) flag_x=1
          content=$OPTARG
          ;;
       y) flag_y=1
          level=$OPTARG
          ;;
      esac
    done

    if [ ! -d $log_dir ]
    then
        echo "log_dir is missing, maybe conf file is not called"
        exit 2
    fi

    date=$(date +%Y-%m-%d)
    final_dir="${log_dir}/${date}"
    if [ ! -d $final_dir ]
    then
        mkdir $final_dir
    fi
    if [ -z $logFileName ]
    then
        echo "logFileName is missing, maybe batch_init was not called"
        exit 2
    fi
    fullPath=${final_dir}/${logFileName}
    echo "[${level}][$(date +%H:%M:%S)]: ${content}" >> $fullPath
}

batch_end

function batch_end {
    exec 1<&6 6<&-
    rm $fifoFile
    if [ ${1:-error} == error ]
    then
        return 2
    else
        return 0
    fi
}

#start capture
batch_init $1
exec > $fifoFile | batch_log

批处理脚本

#!/bin/bash
. /home/batch/lib/core.sh $0
echo "foo bar"
echo "blah"

batch_end
exit $?

但这不起作用:'( 我无法管道exec到我的函数(batch_log)。 有什么想法吗?

你的答案

1 个答案:

答案 0 :(得分:1)

好的,这只是将流重定向到函数的特定语法:

# replace 
exec > $fifoFile | batch_log
# by
exec 1> >( batch_log -y info)
exec 2> >( batch_log -y error)

另见:Append text to stderr redirects in bash