Silence any Commands in any Shell

Omar Aziz - 2 min read
May 3, 2023

  • shell

  • bash

  • stdout

  • silent

Table of Contents

TL;DR

It’s not:

command 2>&1 >/dev/null

It’s:

command 2>&- >&-

This runs a command while discarding its standard output (stdout) and standard error (stderr) messages. It essentially prevents any and all output and any and all error messages from being displayed on the console.

Explanation

command 2>&- >&-: closes both standard output (stdout) and standard error (stderr) file descriptors. As a result, any attempt by the command to write to stdout or stderr will fail, effectively preventing all output.

command 2>&1 >/dev/null: first merges stderr (2) into stdout (1) and then redirects the combined output to /dev/null, a special device that discards all data written to it. While this approach prevents most output, it may not always suppress all output if the command manipulates file descriptors in an unusual way.

stdout?

Standard output - the process conventional output channel. It’s where a process writes regular output data.

stderr?

Standard error - errors and diagnostics output channel. It’s where a process can writes error messages.

Why `2>&- >&-` is Better?

More reliable output suppression: By closing the file descriptors, 2>&- >&- enforces a stricter output suppression, ensuring that no output slips through even if the command reopens the stderr file descriptor or uses a different file descriptor for output.

Handy Function

I have this in my ~/.zshrc:

# Silence any command in any shell
# https://explainshell.com/explain?cmd=%22%24%40%22+2%3E%26-+%3E%26-
silent() {
  "$@" 2>&- >&-
}

Which allows me to do this:

silent yarn install

Shoutout

explainshell, a site that contains 29761 parsed manpages from sections 1 and 8 found in Ubuntu’s manpage repository. You pass it any shell command and it will explain it to you.

https://explainshell.com