• Uncategorized

About linux : How-to-redirect-stderr-and-stdout-to-different-files-in-the-same-line-in-script

Question Detail

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?

Question Answer

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
……………………………………………………
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.
……………………………………………………
Like that:

$ command >>output 2>>error

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

command > merged-output.txt 2>&1

……………………………………………………
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.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.