Problem with my Bash script
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.
I believe the solution suggested by Shawn J. Goff and commented on by Gordon Davisson can be improved by employing modern bash
command substitution syntax. I'm assuming the script and jar are in the same folder:
#!/bin/bash
java -jar "$(cd "$(dirname "$0")"; pwd)/my_app.jar"
echo The present working directory is $(cd "$(dirname "$0")"; pwd)
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.
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
OK, so there are 2 issues you must solve:
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.
Path to the system's installed
java
executable. Ultimately just using barejava
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 usingif [ -e /usr/bin/java ]
, for example, running the first one your code finds.
精彩评论