-2

I have a command cmd that I want to use in a zsh script in the form:

cmd -opt val > info.txt

but I want to redirect stderr from that one line to /dev/null.

Evidently the following does not work:

cmd -opt val > info.txt > /dev/null

How to do it?

Added: Note that I do not want any regular output written to the terminal; all regular output should be written into the specified file info.txt.

murray
  • 737
  • 2
  • 10
  • 28
  • Does this answer your question? [Redirect stderr to /dev/null](https://stackoverflow.com/questions/44758736/redirect-stderr-to-dev-null) – John Bollinger Sep 05 '22 at 15:10
  • In a Bourne-family shell such as `zsh`, you redirect `stderr` by redirecting file descriptor 2 (as opposed to 1 for `stdout`, which is the default for output-redirecting operators). You will find many answers and examples by searching for "redirect stderr". In short, however, use `2>` instead of `>`. – John Bollinger Sep 05 '22 at 15:13
  • @JohnBollinger: NO, using `cmd -opt val 2> info.txt` does *not* do it: while it does send `stderr` to `/dev/null`, it also now sends `stdout` to the terminal, which I do *not* want! I want all normal output from `cmd -opt val` to be written to the file `info.txt` and redirect only any error messages to `/dev/null`. – murray Sep 05 '22 at 15:58
  • What does do what I want is `(cmd -opt val > info.txt) 2> /dev/null`. – murray Sep 05 '22 at 16:09
  • 1
    @murray That's not what John Bollinger is suggesting. In your last comment, the subshell is unnecessary. – chepner Sep 05 '22 at 16:13
  • As I said, @murray, you redirect *`stderr`* via `2>`. This is independent of redirecting `stdout`, which you seemed already to know how to do. – John Bollinger Sep 05 '22 at 17:51

1 Answers1

0

> and 2> are independent and can appear in the same command.

cmd -opt val > info.txt 2> /dev/null

Standard output is redirected to info.txt, and standard error is redirected to /dev/null.

chepner
  • 497,756
  • 71
  • 530
  • 681