将stderr和stdout复制到文件以及ksh中的屏幕 [英] Copy stderr and stdout to a file as well as the screen in ksh

查看:84
本文介绍了将stderr和stdout复制到文件以及ksh中的屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决方案(类似于下面的bash代码),除了Solaris上ksh内的屏幕外,还可以将stdout和stderr都复制到文件中.

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.

以下代码在bash shell中非常有效:

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

由于某种原因,这在Solaris上引发了语法错误.我认为这是因为我无法进行进程替换,并且已经看到一些建议使用mkfifo的帖子,但是我还没有想出可行的解决方案.

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?

推荐答案

您使用的是哪个版本的ksh? ksh88不支持>(),但ksh93支持>()-bash代码在ksh93上应保持不变(除了#!行).

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.

如果您对ksh88感到困惑(可怜的东西!),则可以使用命名管道来模拟bash/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  

上面是第二个版本,可以将stderr重定向到另一个文件.

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

这篇关于将stderr和stdout复制到文件以及ksh中的屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆