如何在Bash脚本中将标准输出和标准错误输出重定向到文件?

7

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

/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>

是否有一种方法可以在脚本内直接输出,或者每次调用脚本都需要使用 >> log_file 2>> err_file?谢谢

3个回答

5

您可以使用这个:

exec >> file
exec 2>&1

在你的bash脚本开头加上exec >>/path/to/logfile。这将把标准输出和标准错误输出都追加到文件中。

4
你可以在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

3

#SBATCH --output=serial_test_%j.log   # Standard output and error log

这将把所有输出,即stdout stderr都发送到一个名为serial_test_<JOBID>.log的单个日志文件中。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接