Sometimes you want to redirect your shell script’s STDOUT/STDERR to a log file. This is pretty simple to do, ie:
./myscript.sh &> output.log
But sometimes you want to do the redirect inside the script itself ( ie, maybe redirecting is conditional, or maybe the file name is conditional on something only the script knows about)
#!/bin/bash exec >> output.log exec 2>&1 >&2 echo "This was printed to stderr" echo "This was printed to stdout"
Or if you want to write to both a file and the terminal:
#!/bin/bash exec 1> >(tee -a output.log) exec 2>&1 >&2 echo "This was printed to stderr" echo "This was printed to stdout"
Stackoverflow has other ways to do it: