Thomas S. Thomas S. - 2 years ago 115
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

$ ./ &> 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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download