How does > /dev/null eat up output streams?
Asked Answered
S

1

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?

Supernational answered 18/6, 2017 at 9:5 Comment(2)
The computer black hole eat it. That's what my colleague told me ;-)Rubinstein
/dev/null is not a real file. It is a pseudofile device that simply discards any data written to it.Dustidustie
F
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.

Fiesole answered 18/6, 2017 at 9:18 Comment(2)
So in effect /dev/null is a symlink to some device whose involvement in any operation triggers this function?Supernational
@Supernational 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).Fleta

© 2022 - 2024 — McMap. All rights reserved.