The /dev/null device is a special file that discards all data written to it but reports that the write operation succeeded. It is typically used for disposing of unwanted output streams of a process. This is usually done by redirection.
/dev/null is creaetd every time on system boot. From the below, we can see that /dev/null is a character device, so it processes data character by character.
$ ls -l /dev/null crw-rw-rw- 1 root root 1, 3 Feb 18 17:24 /dev/null
Size of /dev/null is 0 as we can from the stat command.
$ stat /dev/null File: '/dev/null' Size: 0 Blocks: 0 IO Block: 4096 character special file Device: 6h/6d Inode: 6 Links: 1 Device type: 1,3 Access: (0666/crw-rw-rw-) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2021-02-18 17:24:07.571207521 +0530 Modify: 2021-02-18 17:24:07.571207521 +0530 Change: 2021-02-18 17:24:07.571207521 +0530 Birth: -
Usage in Script
/dev/null is commonly used in scripting. You can tell if an operation is successful. For example, in the script excerpt below, we touch a file and then check to see if the file was updated or created by examining the return code. If operation succeeded, the return code will always be 0.
touch $file 2> /dev/null if [ $? != 0 ]; then echo File creation failed exit 1 else
In the below example, we extract from a tar file, but hide possible errors from the user. This is the kind of thing that many sysadmins will do in a script to reduce the output that their scripts will generate.
#!/bin/bash cd /usr/local/apps tar xf /var/tmp/app.tar 2 >/dev/null if [ $? != 0 ]; then echo extract failed exit 1 fi
Redirecting Output
2 means Standard error and 1 means Standard output. The & means file descriptor1. So 2>&1 redirects standard error to whatever standard output currently points at, while 2>1 redirects standard error into a file called 1. >> means append while > means truncate and write. Either appending to or writing to /dev/null has the same net effect.
Following example, redirects standard error to point at what standard output currently points at, then redirects stdout to /dev/null.
2>&1 >/dev/null
General forms for /dev/null use
- Send standard out to /dev/null
command > /dev/null - Send standard error to /dev/null
command 2> /dev/null - Send both standard out and standard error to /dev/null
command > /dev/null 2>&1