views:

42

answers:

3

He all, i have a problem with my bash script. That's my code:

#!/bin/bash
java -jar my_app.jar
echo "The present working directory is `pwd`"

If i exec it by ./script_name it work, but if i double click on it don't work, i got this error:
"Unable to access jarfile my_app.jar".
Then the pwd output is different !!!

My OS is MacOSX but i need to create a bash script that work in Linux too.

A: 

If you use a graphical tool to execute the script, the current working directory is arbitrary. The current working directory is not a useful concept in graphical applications, and they usually don't use or change it. This means you must include the full path in the call to the java program, or change to the directory where the script is located. Unfortunately, there is no good solution for the latter.

Philipp
I know, but i need to "install" this software in different OS so i can't use full path....any solutions ?
enfix
Do you really need a Bash script? At least on the Linux and OS X systems I use launching a Bash script from a file manager fires up a text editor and doesn't run the script. If it is a graphical application then you should create an application bundle for OS X, which contains all files required for running the application and can be moved around without problems.
Philipp
Just my two cents, you should always use fully qualified paths in your scripts even if you just do a simple java = `which java` (better to have the actual path but this is a bandaid)
kSiR
A: 

The variable $0 should hold the path to the script. You can use dirname to get the directory that the script is in.

java -jar `dirname $0`/my_app.jar
Shawn J. Goff
This will have trouble if anything in the path has a space (common in OS X) -- use `"$(dirname "$0")/my_app.jar"` instead. Also, as Philipp pointed out, there are circumstances where this won't work (though it should be ok for double-clicking the script in the Finder).
Gordon Davisson
A: 

OK, so there are 2 issues you must solve:

  1. Assuming your script and your jar are always installed in the same directory, problem 1 is to identify that directory. That is discussed here. Once you know the script's directory, you can reference your jar file relative to that.

  2. Path to the system's installed java executable. Ultimately just using bare java is straightforward and conventional and relies on the PATH being properly configured. If that doesn't do it for you, just include an ordered list of the most common paths and see if they are executable using if [ -e /usr/bin/java ], for example, running the first one your code finds.

Peter Lyons