[bash] How to redirect both stdout and stderr to a file

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.

Can I log both the stderr and stdout logged to a file?

This question is related to bash stdout io-redirection stderr

The answer is


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'


The simplest syntax to redirect both is:

command &> logfile

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

command &>> logfile

Use:

command >>log_file 2>>log_file

You can do it like that 2>&1:

 command > file 2>&1

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to stdout

Redirect echo output in shell script to logfile Reusing output from last command in Bash Running powershell script within python script, how to make python print the powershell output while it is running Scanf/Printf double variable C Python: How to get stdout after running os.system? How to open every file in a folder Redirect all output to file using Bash on Linux? What does it mean to write to stdout in C? logger configuration to log to file and print to stdout How to get Rails.logger printing to the console/stdout when running rspec?

Examples related to io-redirection

UTF-8 output from PowerShell Redirecting Output from within Batch file Redirect stderr to stdout in C shell Bash write to file without echo? What is /dev/null 2>&1? How to redirect both stdout and stderr to a file Redirect all output to file in Bash Send string to stdin Find and replace in file and overwrite file doesn't work, it empties the file How do I capture all of my compiler's output to a file?

Examples related to stderr

How I can print to stderr in C? Python: How to get stdout after running os.system? Redirect all output to file using Bash on Linux? How to redirect both stdout and stderr to a file How to print to stderr in Python? How to redirect stderr to null in cmd.exe Confused about stdin, stdout and stderr? How can I pipe stderr, and not stdout? How to store standard error in a variable How to redirect and append both stdout and stderr to a file with Bash?