Replace file with hard link to /dev/null

You can make a symbolic link to /dev/null and you don't need to be root:

ln -s /dev/null log.txt

# cp -a /dev/null log.txt

This copies your null device with the right major and minor dev numbers to log.txt so you have another null.

Devices are not known by name at all in the kernel but rather by their major and minor numbers. Since I don't know what OS you have I found it convenient to just copy the numbers from where we already know they are. If you make it with the wrong major and minor numbers, you would most likely have made some other device, perhaps a disk or something else you don't want writing to.


The other answers here will probably work. In particular, the symlink solution is probably going to be the easiest solution. I offer this mainly for completeness.

The solutions involing mknod (or cp -a) become problematic if the filesystem containing the file doesn't support devices (e.g., it was mounted with the nodev option, for example). And of course, hard links across filesystems simply won't work.

An alternative to hard links or creating new devices nodes is to use bind mounts, which let you mount a file or directory from one part of your filesystem tree onto another. So, for example, you can run:

mount -o bind /dev/null /path/to/log.txt

This acts a lot like a hard link, but:

  • It can operate across filesystems (because it's not based on filesystem inodes like a hard link)
  • It works on read-only filesystems (because you're not actually modifying the filesystem)

For a complete example:

bash-4.3# ls -l /var/log/boot.log
-rw-r--r--. 1 root root 7436 Dec 19 10:00 /var/log/boot.log
bash-4.3# mount -o bind /dev/null /var/log/boot.log
bash-4.3# ls -l /var/log/boot.log
crw-rw-rw-. 1 root root 1, 3 Dec 19 09:58 /var/log/boot.log
bash-4.3# echo words words words > /var/log/boot.log
bash-4.3# ls -l /var/log/boot.log
crw-rw-rw-. 1 root root 1, 3 Dec 19 09:58 /var/log/boot.log