Friday, June 29, 2012

Tabular format output in bash using column -t

Often, commands in bash produce data that contains many similar lines that contain same fields with different values. Many times the data across these lines is not aligned because of different number of characters in values. In such scenarios column -t can help print this output in a pretty tabular way.


pankaj-> mount
/dev/disk0s2 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)


pankaj-> mount | column -t

/dev/disk0s2  on         /     (hfs,    local,    journaled)
devfs             on         /dev  (devfs,  local,    nobrowse)


As you can see piping output of mount to column with -t option prints it in a tabular format that is much more readable. By default column -t uses space as table column delimiter but it can be changed to anything else very easily:


pankaj-> cat /etc/passwd
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false


pankaj-> cat /etc/passwd | column -t -s:                                                                                                               nobody                                           *  -2  -2  Unprivileged User              /var/empty          /usr/bin/false
root                                                 *  0   0   System Administrator           /var/root           /bin/sh
daemon                                           *  1   1   System Services                /var/root           /usr/bin/false


Here the colon(:) has been used as table delimiter.


Friday, June 15, 2012

Bash: switch folders quickly with $CDPATH

Most unix users have a few favorite folders for storing source repositories and other stuff they work on daily. There is a feature in Bash that makes it very easy to switch to these folders and it's very simple to use. Just add these folders to the CDPATH environment variable.

e.g. put this in your .profile 
export CDPATH=:~/src:~/work

Different folders are separated by colon. A colon at start or end is shortcut for indicating the home directory. 

What you get:
  1. You can switch to any folders under the folders specified in $CDPATH by just providing the folder name without specifying the full path. e.g.
    to switch to "~/src/graphite" you can just say "cd graphite"
  2. You also get tab completion based on folders under CDPATH folders. This is incredibly useful.
  3. If a folder with same name is present in multiple locations then the current directory gets the highest preference followed by the order of folders specified in $CDPATH. This makes sure that CDPATH doesn't confuse your existing workflow in any way, as current directory always gets priority.
This is one of those tricks you spend five minutes on one day and then enjoy the benefits for the rest of your life.