7

I want to add a command to my bash script that directs all stderr and stdout to specific files. From this and many other sources, I know that from the command line I would use:

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

However, I want something inside my script, something akin to these slurm flags:

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

<code>

Is there a way to direct output from within a script, or do I need to use >> log_file 2>> err_file every time I call the script? Thanks

Josh
  • 1,210
  • 12
  • 30

3 Answers3

5

You can use this:

exec >> file
exec 2>&1

at the start of your bash script. This will append both stdout and stderr to your file.

sportzpikachu
  • 831
  • 5
  • 18
4

You can use this at the start of your bash script:

# Redirected Output
exec > log_file 2> err_file

If the file does exist it is truncated to zero size. If you prefer to append, use this:

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

If you want to redirect both stdout and stderr to the same file, then you can use:

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

If you prefer to append, use this:

# Appending Redirected Output
exec >> log_file 2>&1
mcoolive
  • 3,805
  • 1
  • 27
  • 32
3

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

This will send all output, i.e stdout and stderr to a single log file called serial_test_<JOBID>.log

Ref: https://help.rc.ufl.edu/doc/Sample_SLURM_Scripts

tallamjr
  • 1,272
  • 1
  • 16
  • 21