tags:

views:

803

answers:

2

I have a java CLI script that converts rgb names to hexcodes (e.g. 144 132 146 becomes #908492). However, I want to be able to run it from any terminal. I put a bash script in the same folder so it could run the file:

The bash script is simple enough, just:

#!/bin/bash
java rgb2hexConv $1 $2 $3

However, when I run the code through the PATH, I get errors related to the file rgb2hexConv not being found.

Diagram:

/
  /home/
    /home/me/
      /home/me/someRandomDir/ (running from here does not work)
      /home/me/utils/ (in path) (running from here works)
        - rgb2hex (bash script)
        - rgb2hexConv.class (java program)

My guess is that it's looking for rgb2hexConv in /home/me/someRandomDir/ as opposed to /home/me/utils/. Is there anyway to get the directory of the bash script?

EDIT: Changing the script to use ./rgb2hexConv gives the following:

Exception in thread "main" java.lang.NoClassDefFoundError: //rgb2hexConv
Caused by: java.lang.ClassNotFoundException: ..rgb2hexConv
// long stack trace removed
Could not find the main class: ./rgb2hexConv.  Program will exit.

(The bit at the end of the first line is not a comment, but actual output)

EDIT 2: After an attempt at using $0 the following output was recieved

Exception in thread "main" java.lang.NoClassDefFoundError: /home/me/utils/rgb2hex/rgb2hexConv Caused by: java.lang.ClassNotFoundException: .home.me.utils.rgb2hex.rgb2hexConv // Long Stack Trace Could not find the main class: /home/me/utils/rgb2hex/rgb2hexConv. Program will exit.

Two things about this:

  1. $0 contains the file name as well as a directory
  2. The java command seems to be replacing "/" with ".".
+2  A: 

$0 variable would contain the full path to the. So, the following should work:

java -cp $(dirname $0) rgb2hexConv $1 $2 $3

-cp has been added as per suggestion of Macha.

Alan Haggai Alavi
$0 includes the full filename aswell as the dir.
Macha
Thanks for pointing it out. I have corrected it.
Alan Haggai Alavi
I tried that and it didn't work. So I looked up the docs for the java command and it only works for the current directory. If you want to use a different dir, you have to tell it so using the -cp argument.
Macha
Edit in about -cp (see my answer) and I'll accept this one.
Macha
Still wrong. Should be "java -cp $(dirname $0) rgb2hexConv $1 $2 $3". The directory is the value of -cp, and the filepath is a seperate arg.
Macha
A: 

The following amendment fixed it:

#!/bin/bash
java -cp $(dirname $0) rgb2hexConv $1 $2 $3

It appears you need the -cp modifier on the java command to tell it to search certain directories. And you need to use dirname to get the directory of $0

Macha