Friday, September 05, 2008

Function redirection

I just came across this:
function myfunc {  
    echo 'Hollow world' 
} > outfile

Works with Bourne style functions as well, and is in the POSIX standard. It should not be a surprise, since it just follows the same standard as 'if' and loops, but I have never seen it before. It certainly is not our shell course (yet). Seen it before?

Here is a neat trick:

outfile=one.out

function myfunc {
echo 'Hollow world'
} > $outfile

outfile=two.out
myfunc

Which file gets written to, one.out or two.out? Interestingly it is two.out. In other words the variable is resolved at runtime, not function declaration time.