How to redirect stderr and stdout to different files in the same line in script?

LinuxBash

Linux Problem Overview


I know this much:

$ command 2>> error

$ command 1>> output

Is there any way I can output the stderr to the error file and output stdout to the output file in the same line of bash?

Linux Solutions


Solution 1 - Linux

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Solution 2 - Linux

Try this:

your_command 2>stderr.log 1>stdout.log

More information#

The numerals 0 through 9 are file descriptors in bash. 0 stands for standard input, 1 stands for standard output, 2 stands for standard error. 3 through 9 are spare for any other temporary usage.

Any file descriptor can be redirected to a file or to another file descriptor using the operator >. You can instead use the operator >> to appends to a file instead of creating an empty one.

Usage:

file_descriptor > filename

file_descriptor > &file_descriptor

Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.

Solution 3 - Linux

Like that:

$ command >>output 2>>error

Solution 4 - Linux

Or if you like to mix outputs (stdout & stderr) in one single file you may want to use:

command > merged-output.txt 2>&1

Solution 5 - Linux

Multiple commands' output can be redirected. This works for either the command line or most usefully in a bash script. The -s directs the password prompt to the screen.

Hereblock cmds stdout/stderr are sent to seperate files and nothing to display.

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

Hereblock cmds stdout/stderr are sent to a single file and display.

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

Hereblock cmds stdout/stderr are sent to separate files and stdout to display.

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

Depending on who you are(whoami) and username a password may or may not be required.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser784637View Question on Stackoverflow
Solution 1 - LinuxSujoyView Answer on Stackoverflow
Solution 2 - LinuxQuintus.ZhouView Answer on Stackoverflow
Solution 3 - LinuxDidier TrossetView Answer on Stackoverflow
Solution 4 - Linuxztank1013View Answer on Stackoverflow
Solution 5 - LinuxrahogaboomView Answer on Stackoverflow