Search code examples
linuxbashhttp-redirectstdoutstderr

Redirecting all commands stdout/stderr to a log file from within a script


I've read how to log certain scripts or commands individually, but nothing on how to log all commands from within a BASH shell. What I want to do is:

  • User runs script. (script logs stdout/stderr from now on to a logfile)
  • User does other stuff/runs other commands/echoes/etc and all of these are logged in logfile.

A less wordy / more codey example:

exec > >(tee logfile.log) when typed in by the user does exactly what I want to do. It logs stdout to logfile.log and will continue to do so until the bash shell is closed. However, running this very command as a script does not do this. I want it to.


Solution

  • You can't do this in a script that runs under its own shell (i.e. it starts with #!/bin/bash and you chmod +x and invoke it like an executable). The redirect affects the subshell but it can't reach the parent to do what you want. You can . the file (as in . ./myscript.sh) which will execute the commands in your shell and then you can redirect things as you want.

    The other way to do it would be for your script to start a subshell itself (which would inherit stdin, stdout, stderr). This is what the script command does. It logs everything to a file named (by default) typescript until the user exits the subshell.