Linux Labs

First steps / Stage 11 of 15

Where a command's output goes

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 6 · on a machine · 8 min

Both streams in one file, or nowhere

Sometimes you want the error messages in the same file as the result. Sometimes they just get in the way of reading the output.

2>&1 means: send stream 2 wherever stream 1 is going right now. The & before the 1 marks a stream number, as opposed to a file named "1". A line can hold several redirections, and their order matters — try it on two commands.

Exercise · look

Swap the order of the redirections

In ~/stream-lab, run the two search commands — they differ in the order of the redirections — and then count the lines with the word denied in all.txt.

First, predict

In the first command, 2>&1 comes before > all.txt. Where will the Permission denied messages end up?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

The shell reads redirections from left to right. In the first command, 2>&1 comes first: at that moment stream 1 still goes to the screen, so stream 2 went there too. Then > moved stream 1 alone into the file. In the second command, > first sent stream 1 to all.txt, and 2>&1 sent stream 2 after it. Both streams in one file is > file 2>&1, in exactly that order.

An unwanted stream is thrown away into /dev/null, a special file that accepts any text and keeps nothing. find /etc -name '*.conf' 2> /dev/null prints the paths it finds and nothing else.

Warning

2> /dev/null throws away every error message of the command, the useful ones too. Discard the error stream once you already know what is in it.

Check yourself 1 question

You are looking for your reports across the whole system: find / -name 'report*'. The paths you need are lost among hundreds of Permission denied lines. What do you do?

  • > throws away stream 1 — the very paths you found — and the access refusals stay on the screen.

  • 2>&1 sends stream 2 wherever stream 1 goes — to the screen. The refusals stay among the paths.

  • >> appends stream 1 to /dev/null: the paths found disappear, and the refusals stay on the screen.

find prints access refusals to stream 2, and 2> /dev/null throws them away. The paths found go to stream 1 and are still printed on the screen.

Ubuntu 24.04
Loading…