使用fifo和tee命令让Linux程序重定向到标准输出和文件      
allen2660 +
    

使用fifo和tee命令让Linux程序重定向到标准输出和文件

背景

有这样一个脚本,正常的流运行过程中,要有一个后台进程监控其标准输出。而前端也要看到其标准输出。

tee命令

TEE(1)                                                                              User Commands                                                                             TEE(1)

NAME
   tee - read from standard input and write to standard output and files

SYNOPSIS
   tee [OPTION]... [FILE]...

DESCRIPTION
   Copy standard input to each FILE, and also to standard output.

   -a, --append
          append to the given FILEs, do not overwrite

   -i, --ignore-interrupts
          ignore interrupt signals

   --help display this help and exit

   --version
          output version information and exit

正常情况下,可以这样使用:

sh my_script.sh | tee ${logfile}

方法

使用exec命令将前台进程的输出重定向到fifo文件中,在后台启动一个cat fifo_file | tee log_file将输出同时在stdout和log_file中显示。

logfile=test.log
fifofile=test.fifo

mkfifo $fifofile
cat $fifofile | tee $logfile &

exec 1>$fifofile
exec 2>&1

# some commands to produce normal and error output
cal
badcommand to generate stderr messages
#

#该命令向tee命令发送一个EOF,使其结束
print "\015"

参考

man tee fifo

点击查看评论