78

I want to run a program (google-chrome) in the background, but prevent it from outputting any messages to the terminal.

I tried doing this:

google-chrome 2>&1 1>/dev/null &

However, the terminal still fills up without messages like:

[5746:5746:0802/100534:ERROR:object_proxy.cc(532)] Failed to call method: org.chromium.Mtpd.EnumerateStorag...

What am I doing wrong? How do I redirect all the output to /dev/null?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Benubird
  • 18,551
  • 27
  • 90
  • 141

3 Answers3

87

Redirection operators are evaluated left-to-right. You wrongly put 2>&1 first, which points 2 to the same place, as 1 currently is pointed to which is the local terminal screen, because you have not redirected 1 yet. You need to do either of the following:

2>/dev/null 1>/dev/null google-chrome &

Or

2>/dev/null 1>&2 google-chrome &

The placement of the redirect operators in relation to the command does not matter. You can put them before or after the command.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Martinez
  • 2,693
  • 1
  • 16
  • 19
51

In the section Redirection, Bash's reference manual says:

The operator [n]>&word is used [...] to duplicate output file descriptors

To redirect both standard error and standard output to file you should use the form

&>file

With regard to your case, that means substitute

2>&1 1>/dev/null

with

&>/dev/null
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1146332
  • 2,630
  • 1
  • 15
  • 19
  • 11
    `>/dev/null 2>&1` is maybe more portable than `&>/dev/null`? – Campa Jul 30 '15 at 07:53
  • @Campa what does portable mean here? That the redirection with & will not work in some environments? If yes under what circumstances would it not work? Edit: Found my answer here: https://unix.stackexchange.com/a/434431/325410 – Nick Russler Sep 17 '20 at 10:15
  • 1
    Yep, exactly Nick, `&>` is bash jargon and will/might not work in other shells. – Campa Sep 21 '20 at 12:02
3

It seems that syntax is different:

./a.out 1>/dev/null 2>&1 &

See the devices for FD = 2 are different when ./a.out 1>/dev/null 2>&1 and ./a.out 2>&1 1>/dev/null &

1) FD=2 points to /dev/null

>./a.out 1>/dev/null 2>&1 &
[1] 21181
>lsof -p `pidof a.out`
COMMAND   PID            USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
a.out   21181 xxxxxxxxxxxxxxx    0u   CHR 136,43      0t0        46 /dev/pts/43
a.out   21181 xxxxxxxxxxxxxxx    1w   CHR    1,3      0t0      3685 /dev/null
a.out   21181 xxxxxxxxxxxxxxx    2w   CHR    1,3      0t0      3685 /dev/null

2) FD=2 points to /dev/pts/43

>./a.out 2>&1 1>/dev/null &
[1] 25955
>lsof -p `pidof a.out`
COMMAND   PID            USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
a.out   25955 xxxxxxxxxxxxxxx    0u   CHR 136,43      0t0        46 /dev/pts/43
a.out   25955 xxxxxxxxxxxxxxx    1w   CHR    1,3      0t0      3685 /dev/null
a.out   25955 xxxxxxxxxxxxxxx    2u   CHR 136,43      0t0        46 /dev/pts/43