Skip to content

Instantly share code, notes, and snippets.

@brianloveswords
Last active October 16, 2015 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianloveswords/24698bde59db865a2642 to your computer and use it in GitHub Desktop.
Save brianloveswords/24698bde59db865a2642 to your computer and use it in GitHub Desktop.

echo example

echo writes characters to stdout (file descriptor 1) which is usually connected to your terminal. You can read way too much about file descriptors here: https://en.wikipedia.org/wiki/File_descriptor

$ echo "hi"
hi

When IO is redirected, instead of hooking up the program's file descriptor 1 to the terminal, it tries to open the file and uses that as the endpoint of file descriptor 1. The program itself doesn't have to know or care that this is happening.

$ echo "hi" > greeting.txt

The above is actually shorthand for this, which is more explicit about which file descriptor is being redirected. Every program also receives file descriptor 2, which is used for stderr.

$ echo "hi" 1> greeting.txt

fd_test example

I wrote this little rust program to illustrate file descriptors. Even if you don't know rust it should hopefully be readable enough to understand what's going on!

use std::fs::File;
use std::io::Write;
use std::os::unix::io::FromRawFd;

fn main() {
    // Open file descriptor 1, aka stdout
    let mut stdout =  unsafe { File::from_raw_fd(1) };

    // Open file descriptor 2, aka stderr
    let mut stderr =  unsafe { File::from_raw_fd(2) };


    // Write some awesome stuff to stdout
    stdout.write_all(b"this is on stdout\n");

    // Now we'll write some cool stuff to stderr
    stderr.write_all(b"this is on stderr\n");
}

Running fd_test gives us this:

$ fd_test
this is on stdout
this is on stderr

We can redirect file descriptor 1...

$ fd_test 1> stdout.txt
this is on stderr

or file descriptor 2...

$ fd_test 2> stderr.txt
this is on stdout

...or both!

$ fd_test 1> stdout.txt 2> stderr.txt

Note that my program doesn't have to change at all to be able to write to the terminal or the file system. This is really powerful: by using the standard streams we empower the users of our program to combine and redirect output as they see fit!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment