Discarding Output with /dev/null
In this page:
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
#!/bin/bash
echo "you will not see this" > /dev/null
echo "but this still prints"
Login to try C/C++/Java/PHP code in the editor
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
#!/bin/bash
ls not_a_real_file 2> /dev/null
echo "script continued despite the hidden error, exit was: $?"
Login to try C/C++/Java/PHP code in the editor
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
#!/bin/bash
if command -v ls > /dev/null 2>&1; then
echo "ls is available"
fi
Login to try C/C++/Java/PHP code in the editor
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
#!/bin/bash
while read -r line < /dev/null; do
echo "never printed: $line"
done
echo "loop finished immediately because /dev/null is empty"
Login to try C/C++/Java/PHP code in the editor
- Redirecting only stdout to
/dev/nulland being surprised that error messages still show up; stderr needs its own redirection. - Trying to read meaningful data back out of
/dev/null; it always produces empty input, it is a one-way discard. - Redirecting to
/dev/nullwhen you actually wanted to capture the output for later inspection, losing information you needed.
/dev/nulldiscards anything written to it and always reads as empty.cmd > /dev/nullsilences stdout;cmd 2> /dev/nullsilences stderr;cmd &> /dev/nullsilences both.- Silencing output is common when you only care about a command's exit status, not its text.
/dev/nullalso works as an empty input source when redirected with<.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null