Skip to main content
1 of 4
clk
  • 2.2k
  • 1
  • 20
  • 25

exec 2>>/tmp/history.log 1> >(tee -a /tmp/history.log >&1) may work for you, but there's no guarantee the order will be correct. This ordering appears to be a well-known problem, according to here and here.

This command redirects stderr to the history file with 2>>/tmp/history.log, then tees stdout to the same file using 1> >(tee -a /tmp/history.log. Finally, it directs it back to stdout: >&1.

There's a caveat with this method. In a few tests I've done, there seems to be an error in the ordering of the output if the first entry is returned without an error.

For instance, I used find /etc/ -name interfaces as a test. The output of this command alone is:

$ find /etc/ -name interfaces
/etc/network/interfaces
find: `/etc/lvm/backup': Permission denied
find: `/etc/lvm/archive': Permission denied
find: `/etc/cups/ssl': Permission denied
/etc/cups/interfaces
find: `/etc/ssl/private': Permission denied
find: `/etc/polkit-1/localauthority': Permission denied

When I run find /etc/ -name interfaces 2>>output 1> >(tee -a output >&1) in a script, the output file contains this:

+ find /etc/ -name interfaces
++ tee -a output
find: `/etc/lvm/backup'/etc/network/interfaces
: Permission denied
find: `/etc/lvm/archive': Permission denied
find: `/etc/cups/ssl': Permission denied
find: `/etc/ssl/private': Permission denied
/etc/cups/interfaces
find: `/etc/polkit-1/localauthority': Permission denied

Notice that this part of stderr has been split across two lines:

find: `/etc/lvm/backup': Permission denied

However, when I test find /home -name test_file, the first result is from stderr and the problem goes away:

$ find /home -name test_file
find: `/home/lost+found': Permission denied
find: `/home/user/.config/enchant': Permission denied
/home/user/test2/test_file
find: `/home/user/.gconf/apps/gedit-2': Permission denied
/home/user/test/test_file

Output file contents:

+ find /home -name test_file
++ tee -a output
find: `/home/lost+found': Permission denied
find: `/home/user/.config/enchant': Permission denied
find: `/home/user/.gconf/apps/gedit-2': Permission denied
/home/user/test2/test_file
/home/user/test/test_file

As expected, though as mentioned above, the ordering is inconsistent.

clk
  • 2.2k
  • 1
  • 20
  • 25