Search code examples
bashstdoutstderr

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


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


Solution

  • 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