LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   redirecting stderr to file (https://www.linuxquestions.org/questions/linux-software-2/redirecting-stderr-to-file-607297/)

SPF 12-17-2007 04:55 AM

redirecting stderr to file
 
Hi,

I want to store bash's debug information into a file like this:
bash -x bashscript.sh 2>&1 > debug.log

But when I open debug.log, the stderr info isn't there.

example:

$ cat example.sh
#!/bin/bash
echo hi
$ bash -x example.sh 2>&1 > debug.log
+ echo hi
$ cat debug.log
hi
$

It seems that there is a hidden channel that outputs "+ echo hi" to the terminal. I tried to find it, but I was unsuccessful.

colucix 12-17-2007 04:59 AM

The order is important. If you redirect standard error to standard output without previously redirecting standard output to a file, standard error still goes to the terminal. The following should work
Code:

bash -x bashscript.sh > debug.log 2>&1

SPF 12-17-2007 05:02 AM

it still confuses me.

colucix 12-17-2007 05:20 AM

Why? When you specify
Code:

2>&1
the number 2 and 1 are the file descriptors of standard error and standard output respectively. A file descriptor is an identifier which is assigned by the shell to keep track of open files (you may consider standard input, output and error as files for these purposes). When the shell reads your command line it executes things in the order you have placed them. So, first
Code:

2>&1  # standard error is redirected to standard output
      # and since standard output is still redirected to
      # the terminal the standard error is redirected to
      # the terminal too (unesuful, because it was already)

second
Code:

> some_file  # equal to 1> some_file
              # redirects standard output to a file, but you're
              # not telling anything about standard error, that
              # is kept redirected to the terminal

In other words, the shell does not put redirection together simply because they appear on the same command line. Instead, redirections are executed in sequence: it is your care to specify them in the correct order. I hope it's a little more clear, now.

SPF 12-17-2007 06:56 AM

So:
bash -x bashscript.sh 2>&1 > debug.log

is basicly the same as:
bash -x bashscript.sh > debug.log

because errors go to the terminal by default.

I see it this way, because you are already writing to the file (because it is at the front of the command), all other redirections that come later, pointing to channel 1, will be added to the file (because channel 1 is already being redirected).

Thanks for the explanation colucix!


All times are GMT -5. The time now is 08:58 AM.