'How to find file path to a bash file when the folder is renamed or moved to a new drive?

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.



Solution 1:[1]

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

Solution 2:[2]

You can store the full path of the working directory using the environement variable $PWD, like in this example (done in 5min, it is just to show you how it is works) :

#!/bin/bash
DIR=$PWD
gamePath='java -jar '$DIR'/game.jar'
echo $gamePath

Wherever I will execute this script, it will shows up the working directory even if I change the name of the parent. Let me show you :

enter image description here

You can see that $PWD environnment variable works great. Now, I will change the directory name from TestFolder to TestFolderRenamed and execute the script again :

enter image description here

So, in your case, change your code as following :

#! /bin/bash
DIR=$PWD
java -jar "$DIR/game.jar"

It should works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tripleee
Solution 2 Jeriko