【问题标题】:bash script that directs stderr to file, stdout+stderr to terminal, and returns exit code将 stderr 指向文件、stdout+stderr 指向终端并返回退出代码的 bash 脚本
【发布时间】:2012-11-19 09:55:58
【问题描述】:

这是对我在System.exit return code isn't detected by bash eval 中的意图的更好表述。我需要一个 bash 脚本

  1. 运行一个应用程序(在我的例子中是一个 java 应用程序)
  2. 将 stderr 定向到文件
  3. 将 stderr + stdout 指向终端
  4. 返回应用的退出代码

出于某种原因,这很难做到,尽管在我看来它像是企业应用程序的标准配置...... 谢谢!

[编辑]

通过包装此脚本来测试解决方案:

#!/bin/sh
echo "This is Standard Out"
echo "This is Standard Error" >&2
cat meow

【问题讨论】:

    标签: bash error-handling stdout stderr


    【解决方案1】:

    这将满足您的要求:

    #!/bin/bash
    
    errlog="/var/log/my_app"
    
    exec 2> >(tee "$errlog")
    
    java -jar /path/to/app.jar
    
    exit $?  
    

    解释

    • exec 2 >catch STDERR(如果你在右边提供了一个文件,STDERR会在这个文件中被重定向,不会在终端上更多)
    • >( ) 是一个 bash process substitution(这会在后台创建文件描述符)
    • tee 既可以在终端上显示 STDERR 也可以将 STDERR 保存到日志文件中

    【讨论】:

    • 这很棒。那么我什么时候想在没有进程替换的情况下使用 tee 呢?
    • tee 对于在终端上显示和写入文件都很有用:pastie.org/5468341 请参阅man 1 tee
    【解决方案2】:
    # Save old stdout
    exec 3>&1
    # Redirect stderr to pipe, stdout to saved descriptor, pipe goes to tee
    app_command 2>&1 >&3 | tee errorfile
    # close temporary descriptor now that app is done
    exec 3>&-
    

    【讨论】:

      猜你喜欢
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2012-03-09
      • 2016-03-29
      • 2022-01-18
      • 2011-03-02
      相关资源
      最近更新 更多