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.