Copy stderr and stdout to a file as well as the sc

2019-04-01 02:13发布

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?

3条回答
迷人小祖宗
2楼-- · 2019-04-01 03:02

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楼-- · 2019-04-01 03:04

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-01 03:10

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
查看更多
登录 后发表回答