How to make an Apple Script use its local directory?

I am trying to bundle a .jar executable into an application using the solution provided here: How to create a .app folder from an executable .jar?. I deduced that main.script inside Contents -> Resources -> Scripts is using the computer's global directories, not the application's local directory. Thus, it fails. I found a proposed solution on this page: Wrong working directory, if bash script is opened via double-click. Unfortunately, even this code does not seem to function as intended. For demonstration, I have placed the .jar in the same folder as the script. Here is is the AppleScript code I am trying to use:

do shell script "DIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )
cd \"${DIR}\"

java -jar execute.jar"

Note that the Bash quotation marks are escaped; here is the raw code:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"

java -jar execute.jar

The first line ought to find the directory of the script, the second ought to navigate to that directory, and the third ought to find and run "execute.jar." As I've said, it doesn't. I would troubleshoot more if I knew enough Bash—this is the most in-depth I've ever gone. I verified all three lines independently, which means that the DIR definition is picking its directory off of a freshly-opened Bash/Terminal, independent of the script.

Isn't this sort of like "the chicken or the egg?" The DIR function gives the current directory, which is then used to set the current directory with cd?


This is how I'd handle a scenario such as you've described.

I'd place the execute.jar file in the Resources folder within the application bundle, e.g.:

../Untitled.app/Contents/Resources/

Then use the following example AppleScript code within the AppleScript script that is a part of the AppleScript application bundle:

set pathToJAR to ¬
    quoted form of ¬
    POSIX path of ¬
    (path to resource "execute.jar")

set shellCMD to ¬
    {"/usr/bin/java -jar ", pathToJAR} ¬
        as string

do shell script shellCMD

Now no matter where the application bundle is saved to or copied/moved to, as coded, it will ascertain its location to the resource, the execute.jar file, and be able to run a do shell script command that will execute the shell command accordingly.


To address your comment:

I have an image that stays next to the .jar and is supposed to open with it. If I manually open the contents of the application bundle and run the .jar, the image is loaded in; if the AppleScript code is run, the image is not found. Any ideas?

Try the following example AppleScript code instead:

set pathToMe to ¬
    quoted form of ¬
    POSIX path of ¬
    (path to me)

set shellCMD to ¬
    {"cd ", pathToMe, ¬
        "Contents/Resources/; ", ¬
        "/usr/bin/java -jar execute.jar"} ¬
        as string

do shell script shellCMD