bashunixdev-null

How does > /dev/null eat up output streams?


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?


Solution

  • >/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.