5

I would like to redirect the STDOUT and STDERR of the whole pipe to /dev/null.

Considering this is my command:

sudo lsof -i:22000 -t | xargs kill -9

I know this is the wrong way of doing it:

sudo lsof -i:22000 -t | xargs kill -9 >/dev/null 2>&1

How can we achieve that since simply adding >/dev/null 2>&1 will not have any effect in the pipe as it will be interpreted as part of the STDIN of xargs kill -9?

Kusalananda
  • 333,661
  • I ran a process with PID 32366. echo 32366 | xargs kill -9 >/dev/null 2>&1 worked for me. This is Bash on Ubuntu 16. – berndbausch Jul 10 '21 at 02:41
  • (sudo lsof -i:22000 -t | xargs kill -9) >/dev/null 2>&1? – Cyrus Jul 10 '21 at 05:33
  • @berndbausch If the command to the left of the pipe produced output on standard error, it would appear in the terminal. Try e.g. { echo err >&2; echo out; } | cat >/dev/null 2>&1 – Kusalananda Jul 10 '21 at 06:31
  • @Kusalananda Agreed. I am a sloppy reader and mostly reacted to the remark "will not have any effect in the pipe ...". What about sudo lsof ... 2>/dev/null | xargs ... >/dev/null 2>&1? It's main problem might be more typing than your answer. – berndbausch Jul 10 '21 at 08:21

1 Answers1

12

The output from the pipeline

sudo lsof -i:22000 -t | xargs kill -9 >/dev/null 2>&1

is not fully redirected to /dev/null since the redirections at the end are only affecting the xargs command, as you noted, leaving the standard error stream of sudo connected to the terminal. The redirections are however not technically "part of the standard input" of xargs. The standard input of xargs comes from the sudo command on the left hand side of the pipe.

You will want to redirect the pipeline as a whole:

{ your pipeline; } >/dev/null 2>&1

i.e.,

{ sudo lsof -i:22000 -t | xargs kill -9; } >/dev/null 2>&1

Or, you could obviously redirect each individual part individually.

Depending on whether this is a "once-liner" throwaway command that you'll never use again, or a line of code that will go into a system-critical maintenance script, you may want to craft the left-hand side of your pipeline in such a way that it does not produce diagnostic messages at all under normal operating circumstances (and hence does not need to have its error messages hidden). Alternatively, you may want to manage the service running on port 22000 through systemd or some equivalent service framework.

Tangentially related:

Kusalananda
  • 333,661
  • This solves so many problems I was having with pipes and that was the only reason I was avoiding using pipes whenever error handling is involved. Thanks a lot! – Nassim Bentarka Jul 11 '21 at 03:13