Short version: I want to take the last two components off the results of readlink -f
and store it in a variable using a single line of BASH script.
Long version: I would like a single line of BASH script to set the JAVA_HOME
variable for the EC2 command-line tools. This variable stores the location of Java's home directory. Using the following I can get the absolute path to the java
binary:
$ readlink -f $(which java)
On my test machine, this outputs:
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
That's perfect except I need to chop off "/bin/java". I could use string replace to do this in my profile like so:
JAVA_HOME=$(readlink -f $(which java))
export JAVA_HOME="${JAVA_HOME%/*/*}"
EDITED: Now the only issue with this is that it's two lines. I've accepted an answer below that makes it one, but it still only works on Linux whereas on OS X one must run ./Commands/java_home
from this to get the real directory.
Extra credit: make it work on OS X (where readlink -f
does not work).