How to redirect both stdout and stderr to a file

BashStdoutIo RedirectionStderr

Bash Problem Overview


I am running a bash script that creates a log file for the execution of the command

I use the following

Command1 >> log_file
Command2 >> log_file

This only sends the standard output and not the standard error which appears on the terminal.

Bash Solutions


Solution 1 - Bash

If you want to log to the same file:

command1 >> log_file 2>&1

If you want different files:

command1 >> log_file 2>> err_file

Solution 2 - Bash

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

Solution 3 - Bash

You can do it like that 2>&1:

 command > file 2>&1

Solution 4 - Bash

Use:

command >>log_file 2>>log_file

Solution 5 - Bash

Please use command 2>file Here 2 stands for file descriptor of stderr. You can also use 1 instead of 2 so that stdout gets redirected to the 'file'

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
Questionsdmythos_grView Question on Stackoverflow
Solution 1 - BashMatView Answer on Stackoverflow
Solution 2 - BashCosti CiudatuView Answer on Stackoverflow
Solution 3 - BashLaurent LegrandView Answer on Stackoverflow
Solution 4 - BashblankaboutView Answer on Stackoverflow
Solution 5 - BashPaulDaviesCView Answer on Stackoverflow