linux - [Solved-6 Solutions] How to redirect and append both stdout and stderr to a file with Bash ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
How to redirect and append both stdout and stderr to a file with Bash ?
Linux - Solution 1:
cmd >>file.txt 2>&1
click below button to copy the code. By - Linux tutorial - team
Bash executes the redirects from left to right as follows:
- >>file.txt: Open file.txt in append mode and redirect stdout there.
- 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.
Linux - Solution 2:
There are two ways to do this, depending on your Bash version.
The classic and portable (Bash pre-4) way is:
cmd >> outfile 2>&1
click below button to copy the code. By - Linux tutorial - team
A nonportable way, starting with Bash 4 is
cmd &>> outfile
click below button to copy the code. By - Linux tutorial - team
You should
- Decide if portability is a concern
- Decide if portability even to Bash pre-4 is a concern
- No matter which syntax you use, not change it within the same script
If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.
Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.
Linux - Solution 3:
In Bash you can also explicitly specify your redirects to different files:
cmd >log.out 2>log_error.out
click below button to copy the code. By - Linux tutorial - team
Appending would be:
cmd >>log.out 2>>log_error.out
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 4:
In Bash 4 (as well as ZSH 4.3.11):
cmd &>>outfile
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 5:
your_command 2>&1 | tee -a file.txt
click below button to copy the code. By - Linux tutorial - team
It will store all logs in file.txt as well as dump them on terminal.
Linux - Solution 6:
Try this command:
You_command 1>output.log 2>&1
click below button to copy the code. By - Linux tutorial - team
Tips:
0, 1, 2...9 are file descriptors in bash. 0 stands for stdin, 1 stands for stdout, 2 stands for stderror. 3~9 is spare for any other temporary usage.
Any file descriptor can be redirected to other file descriptor or file by using operator > or >>(append).
Usage: <file_descriptor> > <filename | &file_descriptor>