Mustapha George
Mustapha George

Reputation: 2527

how does linux shell standard output and error output redirect work when combined?

I am trying to understand fine point of standard and error redirection in linux shell scripting (bourne, bash).

Example 1:

cat file1  > output.txt

or

cat file1  1> output.txt

This redirects contents of file1 to output.txt. Works as expected.


Example 2:

kat file1  2> output.txt

kat command does not exist so error is redirected to output.txt. Works as expected.


Example 3:

cat file1  2>&1 output.txt

Because cat is a valid command and file1 exists, here I would expect same behavior as example 1. Instead I seem to get contents of both files to screen.


Example 4:

kat file1  2>&1 output.txt 

since kat does not exist, I would expect same behavior as example 2. Instead I get error to screen ("-bash: kat: command not found")

as explained in many on-line manuals, example: https://www.gnu.org/software/bash/manual/html_node/Redirections.html

Upvotes: 0

Views: 264

Answers (2)

reichhart
reichhart

Reputation: 889

cat file1 2>&1 output.txt

The shell will set up the redirection (stderr to stdout). After that you will have "left" as command executed by shell:

cat file1 output.txt

That's why you see both contents.

For

kat file1 2>&1 output.txt

it is the same because only

kat file1 output.txt

is left after shell sets the descriptors for the command to be executed. And this can't be found => error message from shell.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409364

The problem is that 2>&1 only tells the shell to redirect file descriptor 2 (standard error) to file descriptor 1 (standard output). It doesn't actually do any redirection of standard output.

For that you have to do it explicitly like

cat file1 > output.txt 2>&1

Note that you have to do the descriptor-redirection last (after the standard output redirection) or it will not work.

This is all explained in the Bash manual page (see the section about redirection).

Upvotes: 3

Related Questions