I've made an executable jar file for a terminal game that can be opened by typing java -jar name.jar
in the Terminal.
Then I made a .sh
file inside the same folder as the jar file to open it by double-clicking the .sh
. I asked how to do this here, where people told me to use the following code in the .sh
.
#! /bin/bash
DIR=$(dirname "$0")
java -jar "$DIR/game.jar"
This worked for a while, but when I renamed the folder, I realised if I move the folder to a pen drive the whole thing stops working and I get this in the Terminal.
Error: Unable to access jarfile /Volumes/Hard
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]
So how to find the file path to the folder the .sh
and the jar are in, regardless of where it is, what its name is and what drive it is on?
Also, I'm using MacOS Mojave 10.14.4 if that's of any importance.
The error looks like the path does contain spaces, like probably /Volumes/Hard Drive/Users/something
. The solution is to quote the command substitution.
Tangentially, don't use upper case for your private variable names. But of course, the variable isn't really necessary here, either.
#!/bin/sh
java -jar "$(dirname "$0")/game.jar"
Nothing in this script uses Bash syntax, so it's more portable (as well as often slightly faster) to use sh
in the shebang. Perhaps see also Difference between sh and bash