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.

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 comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.