Linux 系统中的 /dev/null 文件
- [1. Usage](#1. Usage)
- References
In some operating systems, the null device is a device file that discards all data written to it but reports that the write operation succeeded.
/dev/null
(空设备) 在类 Unix 系统中是一个特殊的设备文件,它丢弃一切写入其中的数据,但报告写入操作成功,读取它则会立即得到一个 EOF。/dev/null
也被称为比特桶或者黑洞 (bit bucket or black hole)。
This device is called /dev/null
on Unix and Unix-like systems, NUL:
(see TOPS-20) or NUL
on CP/M and DOS (internally \DEV\NUL
), nul
on OS/2 and newer Windows systems (internally \Device\Null
on Windows NT), NIL:
on Amiga operating systems, and NL:
on OpenVMS.
In Windows Powershell, the equivalent is $null
. It provides no data to any process that reads from it, yielding EOF immediately. In IBM operating systems DOS/360 and successors and also in OS/360 and successors such files would be assigned in JCL to DD DUMMY
.
1. Usage
The null device is typically used for disposing of unwanted output streams of a process, or as a convenient empty file for input streams. This is usually done by redirection.
空设备通常被用于丢弃不需要的输出流,或作为用于输入流的空文件。这些操作通常由重定向完成。
The /dev/null
device is a special file, not a directory, so one cannot move a whole file or directory into it with the Unix mv
command.
/dev/null
是一个特殊文件,而不是目录,因此不能使用 Unix 命令 mv
将文件移动到其中。使用 rm
命令才是 Unix 中删除文件的正确方法。
This will return an End of File (EOF) character if you try to read it using the cat command.
(base) yongqiang@yongqiang:~$ ls -l /dev/null
crw-rw-rw- 1 root root 1, 3 Jun 17 23:02 /dev/null
(base) yongqiang@yongqiang:~$
(base) yongqiang@yongqiang:~$ echo "yongqiang" > /dev/null
(base) yongqiang@yongqiang:~$
(base) yongqiang@yongqiang:~$ cat /dev/null
(base) yongqiang@yongqiang:~$
(base) yongqiang@yongqiang:~$ stat /dev/null
File: /dev/null
Size: 0 Blocks: 0 IO Block: 4096 character special file
Device: 5h/5d Inode: 3 Links: 1 Device type: 1,3
Access: (0666/crw-rw-rw-) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2024-06-17 23:02:19.040000000 +0800
Modify: 2024-06-17 23:02:19.040000000 +0800
Change: 2024-06-17 23:02:19.040000000 +0800
Birth: -
(base) yongqiang@yongqiang:~$
Redirecting stderr
to stdout
first, and then redirect stdout
to /dev/null
.
command > /dev/null 2>&1
Notice the 2>&1
at the end. We redirect stderr(2)
to stdout(1)
. We use &1
to mention to the shell that the destination file is a file descriptor and not a file name.
So if we use 2>1
, we will only redirect stderr
to a file called 1
.
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] Null device, https://en.wikipedia.org/wiki/Null_device