« Japanese Maple | Main | Olympic Sculpture Park »

Shell exec Tip

The shell exec built-in can be used without a command to perform I/O redirection:

“If no command is given except for I/O redirection, the I/O redirection is permanent and the shell is not replaced. Any file descriptors which are opened or dup(2)'d in this way are made available to other executed commands (note that the Korn shell differs here: it does not pass on file descriptors greater than 2).” — sh(1)

This allows a running shell script to change where standard output goes on the fly, for example to reproduce the gist of a “send output into files that change over time” feature as better implemented by httplog and syslog-ng:

#!/bin/sh while sleep 1; do exec >> `date +log.%H:%M` echo "The time is now `date`" done

Other uses include setting the output log after code first determines the filename based on script arguments.

Technorati Tags: ,