Friday, February 10, 2012

Bash function to show the linked locations of a binary

The which command on Linux will show you the location, from your PATH, that a binary will be executed from.
trastle@w500:~$ which javac

This is very useful, however often you will find that the location in your PATH is actually a symbolic link to another location.
trastle@w500:~$ which java | xargs readlink $1

This in turn can be another symbolic link:
trastle@w500:~$ which java | xargs readlink $1 | xargs readlink $1

This means it can take a few commands to view all the links in play when a command is called. Oddly I find myself doing this quite often so I throw a small function in my .bashrc to help out:
function whichlink
  local loc=`/usr/bin/which $1`;
  echo "$loc"
  while [ -h "$loc" ]
    loc=`/bin/readlink $loc`
    echo "--> $loc"

The output is as follows:
trastle@w500:~$ whichlink javac
--> /etc/alternatives/javac
--> /opt/ibm/java/ibm-java2-i386-60/bin/java

Alternately if you don't want to print all of the links along the way and just want to know the final destination the following is useful:
trastle@w500:~$ readlink -f `which javac`

I am certain at some point I'll want to do this on another machine and text is more reliable than my long term memory. Enjoy.