-
Suppressing command output:
We've already seen how to suppress standard output:
ls -l > /dev/null
And how to suppress both standard output and standard error:
ls -l nonexistent_directory > /dev/null 2>&1
-
Suppressing only error messages:
Sometimes you want to see the output but not the error messages:
ls -l . nonexistent_directory 2> /dev/null
You should see the directory listing, but not the error about the non-existent directory.
-
Using /dev/null as an empty file:
/dev/null
can be used as an empty file input. This is useful for commands that require an input file but you don't want to provide any actual input. For example:
grep "pattern" /dev/null
This command will not produce any output because /dev/null
is an empty file.
-
Testing file existence:
You can use /dev/null
to test if a file exists without producing any output:
if cp Documents/test.c /dev/null 2> /dev/null; then
echo "File exists and is readable"
else
echo "File does not exist or is not readable"
fi
This script attempts to copy test.c
to /dev/null
. If successful, it means the file exists and is readable.
-
Clearing the contents of a file:
You can use /dev/null
to quickly clear the contents of a file:
cat /dev/null > combined_output.log
Check that the file is now empty:
cat combined_output.log
You should see no output, indicating that the file is now empty.