如何从 bash 脚本中将 stdout 和 stderr 重定向到一个文件?

How to redirect both stdout and stderr to a file from within a bash script?

我想在我的 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>

有没有办法直接从脚本中输出,或者我是否需要在每次调用脚本时都使用 >> log_file 2>> err_file?谢谢

你可以使用这个:

exec >> file
exec 2>&1

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

您可以在 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

#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