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

六眼飞鱼酱① 提交于 2019-12-03 17:25:40

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.

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.

JBat

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