【问题标题】:Copy stderr and stdout to a file as well as the screen in ksh将 stderr 和 stdout 复制到文件以及 ksh 中的屏幕
【发布时间】:2012-08-22 14:36:33
【问题描述】:

我正在寻找一种解决方案(类似于下面的 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,但我还没有想出一个可行的解决方案。

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

【问题讨论】:

    标签: shell ksh io-redirection


    【解决方案1】:

    您使用的是哪个版本的 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重定向到不同的文件。

    【讨论】:

    • 这几乎是我所需要的,但这并不能使 STDOUT 和 STDERR 文件描述符分开。如果我调用./script.sh &gt;out.log 2&gt;err.log 之类的脚本,那么所有输出都会转到 out.log,但有些应该转到 err.log
    • Solaris 10 中的 ksh 确实支持进程替换,但显然它不适用于 exec
    • 我猜 tee 进程永远运行。可能我们需要一个清理代码,kill %tee 需要做两次。
    • @shuva tee 从其stdin 获取 EOF(文件结束)时退出。
    【解决方案2】:

    这个怎么样:

    (some commands ...) 2>&1 | tee logfile.txt
    

    -a 添加到tee 命令行,以便后续调用追加而不是覆盖。

    【讨论】:

    • 我不想对每个命令都这样做,理想情况下,我想要一些可以放在脚本顶部的东西,就像上面的例子一样。
    • 我还应该提到它必须在脚本内部完成。我有一个运行脚本的守护进程,该脚本将所有输出捕获到日志文件中,因此我无法控制命令行上的调用。
    【解决方案3】:

    在 ksh 中,以下内容对我来说效果很好

    LOG=log_file.$(date +%Y%m%d%H%M%S).txt
    {
    ls
    date
    ... whatever command
    } 2>&1 | tee -a $LOG
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 2017-05-24
      • 2022-01-18
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多