【问题标题】:Linux - Redirecting part of output to a fileLinux - 将部分输出重定向到文件
【发布时间】:2014-04-09 07:52:09
【问题描述】:

我们可以使用 EXEC 命令将所有的 STDOUT 和 STDERR 重定向到一个 .log 文件,例如:

#!/bin/bash
exec 1> record.log 2>&1
echo begin redirecting

# from the script above, 'begin redirecting' will be redirected to record.log
# then we want to disable the redirecting and restore the STDOUT&STDERR     

echo return to STDOUT and STDERR

# here 'return to STDOUT and STDERR' will be print out

有谁知道如何禁用重定向(STDOUT 和 STDERR)? 这样,我们可以使用 exec 命令将部分输出重定向到文件。 非常感谢。

【问题讨论】:

    标签: linux bash shell redirect exec


    【解决方案1】:

    你可以这样做:

    #!/bin/bash
    
    # Link file descriptor #6 with stdout/stderr
    exec 6>&1 2>&1
    
    exec 1> record.log 2>&1
    echo begin redirecting
    
    # restore and close file descriptor #6
    exec 1>&6 2>&1 6>&-
    
    # from the script above, 'begin redirecting' will be redirected to record.log
    # then we want to disable the redirecting and restore the STDOUT&STDERR     
    
    echo return to STDOUT and STDERR
    

    【讨论】:

    • 冒着挑剔的风险,在恢复之后,它们被合并了。你不应该单独保存它们,例如exec 4>&1 5>&2 然后分别恢复它们,例如exec 1>&4 4>&- 2>&5 5>&-?
    • @John1024:在此脚本中,stdout/stderr 仅一起处理。但是你所建议的也可以做到。我把它留给 OP。
    • @user3514137:很高兴知道,您能否通过单击我的答案左上角的勾号将答案标记为已接受。
    【解决方案2】:

    为什么不用子shell来限制重定向的范围呢?例如

    #!/bin/bash
    
    (
        exec 1> record.log 2>&1
        echo begin redirecting
    
    )
    
    echo This goes to stdout
    

    如果您在内部范围内设置变量,您可能会遇到问题。取决于您的程序的结构。

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2013-10-11
      • 2023-03-19
      • 2014-03-31
      相关资源
      最近更新 更多