0

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

Community
  • 1
  • 1
Neil C. Obremski
  • 18,696
  • 24
  • 83
  • 112

3 Answers3

5
dirname $(dirname $(readlink -f $(which java)))
blueblob
  • 93
  • 5
1

For the Mac OS X version, try this:

dirname $(dirname $(perl -e "use Cwd; print Cwd::abs_path('$(which java)')"))
Dan
  • 4,312
  • 16
  • 28
  • I just ran this on Lion and the output is just `/usr` so I think the Perl is not following symlinks. – Neil C. Obremski Nov 07 '13 at 21:40
  • Sorry @NeilC.Obremski I screwed up the escaping. Fixed now. – Dan Nov 08 '13 at 11:19
  • Thanks @Dan, that *works* but there's something else screwy on OS X w/ Java: it points to a folder that has no `./bin`. Instead there's a `./Commands/java_home` command that has to be run to output the real directory ... what a pain! It appears that I can't make a line of BASH script that works between Linux and OS X. – Neil C. Obremski Nov 08 '13 at 18:25
0

This should work for extracting /bin/java, even on MAC OSX (untested)

echo ${JAVA_HOME##${JAVA_HOME%/*/*}}

epsilon
  • 2,849
  • 16
  • 23