How to redirect output to screen as well as a file?

Solution 1:

You can use the tee command for that:

command | tee /path/to/logfile

The equivelent without writing to the shell would be:

command > /path/to/logfile

If you want to append (>>) and show the output in the shell, use the -a option:

command | tee -a /path/to/logfile

Please note that the pipe will catch stdout only, errors to stderr are not processed by the pipe with tee. If you want to log errors (from stderr), use:

command 2>&1 | tee /path/to/logfile

This means: run command and redirect the stderr stream (2) to stdout (1). That will be passed to the pipe with the tee application.

Solution 2:

script will start an interactive session and log all the output (stdout/stderr etc) to a file, or (with the -c parameter) will run a command and log the output of that.

script -c ~/.abc.sh -f abc.log

Note: in an interactive session, you can stop recording just by exiting the session as you normally would (e.g. exit or Ctrl-D).

For session recording with video playback, you can also try asciinema.