Ryan Li Ryan Li - 2 years ago 67
Bash Question

Referring to a file relative to executing script

In a bash script I'm writing, I use

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

source act.conf.sh

However this only works when running
in the directory containing it, since
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
? Thanks.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download