我正在寻找一种解决方案(类似于下面的 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/