Blangero
Blangero

Reputation: 115

How do I redirect a copy of all output of a shell script?

I want to redirect a copy of all output of a shell script, there's some mount command and some echo in the script.

If I use >> 2>&1, I can't see the output from the command line.
If I use | tee -a the_log_file 2>&1, I can get all output in command line, but in the_log_file, there's no mount error output such as mount.nfs: /mnt/folder is busy or already mounted which I also want in the_log_file

How can I fix this?

Upvotes: 2

Views: 690

Answers (1)

Volker Siegel
Volker Siegel

Reputation: 3585

You need to use
command 2>&1 | tee -a the_log_file
instead of
command | tee -a the_log_file 2>&1

(If you ask me, it's pretty unintuitive that you need to not put the 2>&1 in an unintuitive place in the pipe case! ;) )

For the details, take a look at the Illustrated Redirection Tutorial in Bash Hackers Wiki. The illustration in section Duplicating File Descriptor 2>&1 shows our case:

  ls /tmp/ doesnotexist 2>&1     |                   less

 ---       +--------------+              ---       +--------------+
( 0 ) ---->| /dev/pts/5   |     ------> ( 0 ) ---->|from the pipe |
 ---       +--------------+    /   --->  ---       +--------------+
                              /   /
 ---       +--------------+  /   /       ---       +--------------+
( 1 ) ---->| to the pipe  | /   /       ( 1 ) ---->|  /dev/pts    |
 ---       +--------------+    /         ---       +--------------+
                              /
 ---       +--------------+  /           ---       +--------------+
( 2 ) ---->|  to the pipe | /           ( 2 ) ---->| /dev/pts/    |
 ---       +--------------+              ---       +--------------+

Upvotes: 4

Related Questions