Ryan Li Ryan Li - 7 months ago 9
Bash Question

Referring to a file relative to executing script

In a bash script I'm writing, I use

source
to include the variable defined in a configuration file. The script to be executed is
act.sh
, while the script to be
source
d is
act.conf.sh
, so in
act.sh
I have:

source act.conf.sh


However this only works when running
act.sh
in the directory containing it, since
act.conf.sh
there refers to the file placed under the working directory. Is there a solution to make it refer to the file relative to the executing script without invoking
cd
? Thanks.

Answer

See: BASH FAQ entry #28: "How do I determine the location of my script? I want to read some config files from the same place."

They recommend avoiding the very commonly used $0 variable:

Nothing that reads $0 will ever be bulletproof, because $0 itself is unreliable.

They suggest you use $BASH_SOURCE instead. Something like this:

source "${BASH_SOURCE%/*}/act.conf.sh"

I recommend you check out the page, as they suggest other options as well. They also recommend cd in combination with $BASH_SOURCE in cases where it will work for you.

Comments