Thomas S. Thomas S. - 7 months ago 27
Bash Question

Shell script: redirect output

Our shell script contains the header

#!/bin/bash -x


that causes the commands to also be listed. Instead of having to type

$ ./script.sh &> log.txt


I would like to add a command to this script that will log all following output (also) to a log file. How this is possible?

Answer

You can place this line at the start of your script:

# redirect stdout/stderr to a file
exec &> log.txt

EDIT: As per comments below:

#!/bin/bash -x

# redirect stdout/stderr to a file and still show them on terminal
exec &> >(tee log.txt; exit)