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

Result:

1
2
3

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):

#!/bin/bash
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 🙂

One Comment

  • 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.

Leave a Reply to eNetLogica Technolog Cancel reply

Your email is never shared.Required fields are marked *