Just another WordPress site

Bash stderr/stdout redirection

Today i was writing a little bash script. As i was just interested in the return code of an executed command, i wanted to surpress all output. Usually i always do it like this: cmd 1> /dev/null 2>&1, but today i accidentally did it like this: cmd 2>&1 1> /dev/null. And guess what: suddenly error messages began to appear. I was puzzled.

So it’s time for a litte stdout/stderr redirection tutorial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# redirects stdout (1) and stderr (2) to /dev/null
cmd &> /dev/null
 
# redirects stdout (1) and stderr (2) to /dev/null
cmd 1> /dev/null 2> /dev/null
 
# redirects stdout (1) and stderr (2) to /dev/null
cmd 1> /dev/null 2>&1
 
# redirects stderr (2) to stdout (1) and redirects stdout (1) to /dev/null 
# it will NOT redirect stderr (2) to /dev/null
# This is beceause the stdout was still pointing to itself
# at the time the stderr redirection has been set up.
cmd 2>&1 1> /dev/null

Comments on: "Bash stderr/stdout redirection" (1)

  1. [...] Bash stderr/stdout redirection « Marco’s BlogOct 9, 2011 … Bash stderr/stdout redirection. 10 09 11′. Written by mweber. 0 Comments. Today i was writing a little bash script. As i was just interested in the … [...]

Leave a comment for: "Bash stderr/stdout redirection"

You must be logged in to post a comment.