shell - 将 stderr 和 stdout 复制到文件以及 ksh 中的屏幕

标签 shell ksh io-redirection

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

以下代码在 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 ,但我还没有想出一个可行的解决方案。

有谁知道除了默认位置之外,所有输出都可以重定向到文件的方法吗?

最佳答案

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

如果您坚持使用 ksh88(糟糕的事情!),那么您可以使用命名管道模拟 bash/ksh93 行为:

#!/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 能够重定向到不同文件的第二个版本。

关于shell - 将 stderr 和 stdout 复制到文件以及 ksh 中的屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075527/

相关文章:

shell 脚本以按列方式追加文件

linux - 如果出现问题,如何让 ksh 脚本自行终止?

linux - 命令在命令行和脚本文件中产生不同的结果

linux - 新手 : Script to change directories

c++ - 如何使用C\C++在windows中实现linux管道

linux - 在 Linux 中追加到一个新行

shell - 如何定期保存程序输出的最后一行?

linux - 等到第一个 .jar 文件完成后,再在 for 循环中执行第二个 .jar 文件

linux - 如何检查Linux shell命令是否是只读的?

go - 如何使用 Pipes 分配额外的 ExraFile 以拥有多个输出流?