Thursday, 11 December 2008

Handy Hints in BASH

Ever wanted to diff the output from 2 commands but didn't want to have to write the output to temporary files first? Well bash subshells come to the rescue.

Let's say you want to compare the list of files in 2 different directories. Try this:

diff <(ls /path/to/dir1) <(ls /path/to/dir2)

The bits in brackets are run in a subshell and then we redirect the output of that subshell to the stdin of diff. (On a personal note I prefer to run diff with the -y switch to get a side-by-side diff, but that's me).

Of course you can get really tricky with these things. How about making sure the file permissions are right as well?

diff -y <(ls -l /path/to/dir1 | awk '{print $1, $NF}')
<(ls -l /path/to/dir2 | awk '{print $1, $NF}')

(All that should be on one line. This is my first post so be gentle on me if it comes out looking like an uncombed monkey.)

So, have fun with subshells. And be careful out there.


No comments: