Copy stderr and stdout to a file as well as the screen in ksh

一世执手 提交于 2019-12-05 02:53:17

问题


I'm looking for a solution (similar to the bash code below) to copy both stdout and stderr to a file in addition to the screen within ksh on Solaris.

The following code works great in the bash shell:

#!/usr/bin/bash

# Clear the logfile
>logfile.txt

# Redirect all script output to a logfile as well as their normal locations
exec >  >(tee -a logfile.txt)
exec 2> >(tee -a logfile.txt >&2)
date
ls -l /non-existent/path

For some reason this is throwing a syntax error on Solaris. I assume it's because I can't do process substitution, and I've seen some posts suggesting the use of mkfifo, but I've yet to come up with a working solution.

Does anyone know of a way that all output can be redirected to a file in addition to the default locations?


回答1:


Which version of ksh are you using? The >() is not supported in ksh88, but is supported in ksh93 - the bash code should work unchanged (aside from the #! line) on ksh93.

If you are stuck with ksh88 (poor thing!) then you can emulate the bash/ksh93 behaviour using a named pipe:

#!/bin/ksh 
# Clear the logfile  
>logfile.txt  

pipe1="/tmp/mypipe1.$$"
pipe2="/tmp/mypipe2.$$"
trap 'rm "$pipe1" "$pipe2"' EXIT
mkfifo "$pipe1"
mkfifo "$pipe2"
tee -a logfile.txt < "$pipe1" &
tee -a logfile.txt >&2 < "$pipe2" &

# Redirect all script output to a logfile as well as their normal locations  
exec >"$pipe1"
exec 2>"$pipe2"

date   
ls -l /non-existent/path  

The above is a second version to enable stderr to be redirected to a different file.




回答2:


How about this:

(some commands ...) 2>&1 | tee logfile.txt

Add -a to the tee command line for subsequent invocations to append rather than overwrite.




回答3:


In ksh, the following works very well for me

LOG=log_file.$(date +%Y%m%d%H%M%S).txt
{
ls
date
... whatever command
} 2>&1 | tee -a $LOG


来源:https://stackoverflow.com/questions/12075527/copy-stderr-and-stdout-to-a-file-as-well-as-the-screen-in-ksh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!