Joshua Fox
Joshua Fox

Reputation: 19675

In bash, what's the best way for a script to reference the path of another script?

scripts/a.sh calls scripts/b.sh through source or through sh.

But I cannot be sure that the working directory will be scripts or the parent of scripts or something else.

What is the best practice for referencing b.sh? I can find the directory of the current script, then cd to that directory, and then simply call ./b.sh. But that seems like a lot of code to put into every script that calls another.

Upvotes: 0

Views: 59

Answers (1)

KamilCuk
KamilCuk

Reputation: 141393

There is no need for a cd, cause source or command take a full path. Just get the dir name of the full path of your script and run the script from there.

From bash manual:

0
($0) Expands to the name of the shell or shell script. ....

From man readlink:

-f, --canonicalize
canonicalize by following every symlink in every component of the given name recursively; ...

From man dirname:

dirname - strip non-directory suffix from file name

Altogether:

. "$(dirname "$(readlink -f "$0")")"/b.sh

I've seen some bash scripts that start with something similar to:

DIR=$(dirname "$(readlink -f "$0")")
cd "$DIR"

So the current working directory in a script stays the same, even if user runs it from another directory.

@edit

Like @GordonDavisson suggested in comments, we can also add your dir to PATH:

export PATH="$(dirname "$(readlink -f "$0")")":"$PATH"

Then running:

. a.sh

will search for a.sh script through inside directories listed in PATH variable, which it will find in the first dir.

Upvotes: 1

Related Questions