2

I've used /dev/null a lot in bash programming to send unnecessary output into a black hole.

For example, this command:

$ echo 'foo bar' > /dev/null
$ 

Will not echo anything. I've read that /dev/null is an empty file used to dispose of unwanted output through redirection. But how exactly does this disposal take place? I can't imagine /dev/null writing the content to a file and then immediately deleting that file. So what actually happens when you redirect to this file?

cs95
  • 379,657
  • 97
  • 704
  • 746

1 Answers1

5

>/dev/null redirects the command standard output to the null device, which is a special device which discards the information written to it. It's all implemented via file_operations (drivers/char/mem.c if you're curious to look yourself):

static const struct file_operations null_fops = {
    .llseek     = null_lseek,
    .read       = read_null,
    .write      = write_null,
    .splice_write   = splice_write_null,
};

write_null is what's called when you write to /dev/null. It always returns the same number of bytes that you write to it:

static ssize_t write_null(struct file *file, const char __user *buf,
              size_t count, loff_t *ppos)
{
    return count;
}

That's it. The buffer is just ignored.

tso
  • 4,732
  • 2
  • 22
  • 32
  • So in effect `/dev/null` is a symlink to some device whose involvement in any operation triggers this function? – cs95 Jun 18 '17 at 09:20
  • @cs95 Symbolic links and device nodes are different concepts. Symlinks point to other files while device passes operations to *drivers*, which contains device-specific code to handle all kinds of operations (e.g. `/dev/full` will reject any non-zero writes). – iBug Nov 30 '21 at 10:38