Coder Perfect

In a script, how can I redirect stderr and stdout to distinct files in the same line?

Problem

This is what I know:

$ command 2>> error

$ command 1>> output

Is it possible to output stderr to the error file and stdout to the output file from the same bash line?

Asked by user784637

Solution #1

Simply type command 2>> error 1>> output in a single line.

Note that >> is used to append data to a file that already contains data. >, on the other hand, overwrites any existing contents in the file.

If you don’t wish to append, use command 2> error 1> output.

Because the default file descriptor is the output, you can write 1> as just > for the sake of completeness. As a result, 1> and > are interchangeable.

So, instead of command 2> error 1> output, command 2> error > output is used.

Answered by Sujoy

Solution #2

Try this:

your_command 2>stderr.log 1>stdout.log

In bash, the numbers 0 through 9 are file descriptors. 0 denotes standard input, 1 denotes standard output, and 2 denotes standard error. 3–9 are available for any other temporary use.

Using the operator >, any file descriptor can be redirected to a file or another file descriptor. Instead of creating an empty file, you can use the operator >> to append to one.

Usage:

file_descriptor > filename

file_descriptor > &file_descriptor

I/O Redirection is covered in Chapter 20 of the Advanced Bash-Scripting Guide.

Answered by Quintus.Zhou

Solution #3

Like that:

$ command >>output 2>>error

Answered by Didier Trosset

Solution #4

Alternatively, if you wish to combine outputs (stdout and stderr) into a single file, you can use:

command > merged-output.txt 2>&1

Answered by ztank1013

Solution #5

The output of many instructions can be redirected. This works on the command line and, more importantly, in a bash script. The -s specifies that the password prompt be displayed on the screen.

Here, the stdout/stderr commands are sent to separate files, and there is nothing to display.

sudo -s -u username <<'EOF' 2>err 1>out
ls; pwd;
EOF

The stdout/stderr commands are transmitted to a single file and displayed here.

sudo -s -u username <<'EOF' 2>&1 | tee out
ls; pwd;
EOF

Here, the block cmds stdout/stderr are sent to different files, with stdout being displayed.

sudo -s -u username <<'EOF' 2>err | tee out
ls; pwd;
EOF

A password may or may not be required, depending on who you are (whoami) and your username.

Answered by rahogaboom

Post is based on https://stackoverflow.com/questions/7901517/how-to-redirect-stderr-and-stdout-to-different-files-in-the-same-line-in-script