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 🙂

This entry was posted in Linux & BSD and tagged , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

One Comment

  1. Posted September 17, 2012 at 13:05 | Permalink

    eNetLogica offers SAP Support & Maintenance India, SAP Support India, SEO Noida, SEO services Noida, SEO Services, SEO Company Noida, Website Development Noida, SAP Support Noida.

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>