← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 13 of 13

Discarding Output with /dev/null

/dev/null is a special file that quietly throws away anything written to it, which is useful when you want to silence output you do not care about.

Silencing stdout

Redirecting a command's stdout to /dev/null discards its normal output entirely while still letting the command run and set its exit status normally.

Example: Silencing stdout

bash
#!/bin/bash
echo "you will not see this" > /dev/null
echo "but this still prints"

Silencing stderr Only

Redirecting only file descriptor 2 to /dev/null hides error messages while keeping normal stdout output visible, which is useful when a command's errors are expected and not actionable.

Warning: Silencing errors can hide real bugs; only do it when you have a specific reason to expect and ignore that error.

Example: Silencing stderr Only

bash
#!/bin/bash
ls not_a_real_file 2> /dev/null
echo "script continued despite the hidden error, exit was: $?"

Silencing Everything

&> /dev/null (or > /dev/null 2>&1) discards both stdout and stderr, which is common when a script only cares whether a command succeeded, checked via $?.

Example: Silencing Everything

bash
#!/bin/bash
if command -v ls > /dev/null 2>&1; then
    echo "ls is available"
fi

Using /dev/null as Empty Input

/dev/null can also be used as a source with <, in which case it always immediately signals end-of-file, providing an empty input stream.

Example: Using /dev/null as Empty Input

bash
#!/bin/bash
while read -r line < /dev/null; do
    echo "never printed: $line"
done
echo "loop finished immediately because /dev/null is empty"
Common Mistakes
  1. Redirecting only stdout to /dev/null and being surprised that error messages still show up; stderr needs its own redirection.
  2. Trying to read meaningful data back out of /dev/null; it always produces empty input, it is a one-way discard.
  3. Redirecting to /dev/null when you actually wanted to capture the output for later inspection, losing information you needed.
Chapter Summary
  • /dev/null discards anything written to it and always reads as empty.
  • cmd > /dev/null silences stdout; cmd 2> /dev/null silences stderr; cmd &> /dev/null silences both.
  • Silencing output is common when you only care about a command's exit status, not its text.
  • /dev/null also works as an empty input source when redirected with <.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.