简体   繁体   中英

bash: Run another program in the current directory while running from path

I have a java CLI script that converts rgb names to hexcodes (eg 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 ".".

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM