Tip: Shell redirection

Did you know you can open file descriptors in the shell? My colleague didn’t, so here’s my 30 second summary on file descriptor redirection. It’s a POSIX standard too!

Shell Equivalent in C
# Open a log file on fd 5 for the duration
# of this shell script.
exec 5>/tmp/log
dup2 (open ("/tmp/log", O_WRONLY), 5);
# Send a log message to fd 5.
echo hello >&5
write (5, "hello\n", ..);
# Open fd 6 for input for the duration
# of this shell script.
exec 6</tmp/input
dup2 (open ("/tmp/input", O_RDONLY), 6);
# Read a line from fd 6.
read line <&6
Approximately like doing read on fd 6, but it’s more like fgets in that it reads one line, and it can optionally split the line into whitespace-separated fields.

Redirection is actually far more powerful than this. You can close file descriptors, duplicate them and append to them. But the four uses above are the most common. For the rest, plough through the bash manual page section on redirection here.

About these ads

1 Comment

Filed under Uncategorized

One response to “Tip: Shell redirection

  1. Mace Moneta

    I stopped using file descriptors when bash 4 became available, with the mapfile command.

    mapfile -t -O 1 records < "somefile"

    The above reads the entire file "somefile" into the array "records", starting at index 1.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s