【问题标题】:How to redirect both stdout and stderr to a file from within a bash script?如何从 bash 脚本中将 stdout 和 stderr 重定向到文件?
【发布时间】:2020-04-08 01:53:30
【问题描述】:

我想在我的 bash 脚本中添加一个命令,将所有 stderr 和 stdout 指向特定文件。从this 和许多其他来源,我知道从命令行我会使用:

/path/to/script.sh >> log_file 2>> err_file

但是,我想在我的脚本中加入一些类似于这些 slurm 标志的东西:

#!/bin/bash
#SBATCH -o slurm.stdout.txt # Standard output log
#SBATCH -e slurm.stderr.txt # Standard error log

<code>

有没有办法直接从脚本中输出,还是每次调用脚本时都需要使用&gt;&gt; log_file 2&gt;&gt; err_file?谢谢

【问题讨论】:

    标签: bash stdout stderr


    【解决方案1】:

    你可以用这个:

    exec >> file
    exec 2>&1
    

    在 bash 脚本的开头。这会将 stdout 和 stderr 都附加到您的文件中。

    【讨论】:

      【解决方案2】:
      
      #SBATCH --output=serial_test_%j.log   # Standard output and error log
      
      

      这会将所有输出,即标准输出标准错误发送到一个名为serial_test_&lt;JOBID&gt;.log的日志文件

      参考:https://help.rc.ufl.edu/doc/Sample_SLURM_Scripts

      【讨论】:

        【解决方案3】:

        您可以在 bash 脚本的开头使用它:

        # Redirected Output
        exec > log_file 2> err_file
        

        如果文件确实存在,则将其截断为零大小。如果你喜欢追加,使用这个:

        # Appending Redirected Output
        exec >> log_file 2>> err_file
        

        如果你想将 stdout 和 stderr 都重定向到同一个文件,那么你可以使用:

        # Redirected Output
        exec &> log_file
        # This is semantically equivalent to
        exec > log_file 2>&1
        

        如果你喜欢追加,使用这个:

        # Appending Redirected Output
        exec >> log_file 2>&1
        

        【讨论】:

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