How to write STDOUT and STDERR to different files in bash scripts

So, in your ubuntu docker container, you want to use bash redirection if you want to write the regular script screen logs or out messages to one file and errors to another at the same time.

There are two types of output redirection in bash to handle this scenario,

Standard output

stdout or 1

The STDOUT is the standard output of a shell command or script. We can use “>” or “1>” to redirect them.

Standard Error

stderr or 2

The STDERR, which is any error or warning messages from a script or command. We can use “2>” to redirect them.

Examples of stdout and stderr redirections

Consider the below scenario, where we are running the ls -l towards two files, one exists and the other does not.

We will get the standard output and standard error as follows:

To send the outputs to two different files, we are going to use redirects

The syntax for redirecting stderr and stdout to separate files.

ls -l code.txt try.txt > out.log 2> error.log

Here, the first redirect > instructs the shell to send standard out (1) to the file out.log. You can also use the syntax as 1> out.log

second redirect 2> requests the shell to send error(2) messages to error.log – 2> error.log

Output redirection demo:

bash output redirections to different files

Let us check the output

Redirecting to /dev/null, or silencing the output.

If you want to suppress or silence any one of the output, you can redirect it to /dev/null – which is a system file

Syntax:

ls 1> /dev/null

In this case, the standard output will not be visible or written to the file, instead redirected to /dev/null

Similarly, to ignore all errors by redirecting them to /dev/null, the Syntax is:

ls 2> /dev/null

Please feel free to ask if you have questions.