Bash control structures have redirection too

I found out a useful thing today. You can redirect output of bash control structures as well. Typically useful for for loops, which would need a buffer of some kind otherwise to have it's output sorted, for example.

Check out this not-particularly-useful example

for i in 3 2 1; do 
    echo $i
done | sort -n



What I've proven here is that the output of the for loop goes through the sort pipe, before ending up on your screen. Pretty useful if you're doing some processing inside a for loop, but still want to make use of sorting without having to end up using temporary files.

A more useful example (something I tried today) was listing a bunch of SVN repositories and the times they were last changed (in days):

now=$(date +"%s")

for i in */; do
    mtime=$(date --date "$(svnlook date $i)" +"%s")
    age=$(( ($now - $mtime) / (24 * 3600) ))
    echo $i $age | awk '{printf "%-40s%d\n", $1, $2}' 
done | sort -k 2 -n

The -k option directs sort to use the second column in the for-loop's output. Very useful, imho :)

< Return to main page

You're looking at a very minimalistic archived version of this website. I wish to preserve to content, but I no longer wish to maintain Wordpress, nor handle the abuse that comes with that.