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.
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."
Any solution isn't going to work 100% of the time:
If you need to write a very reusable tool, then taking the correct path as a parameter to your script is going to be the most reliable method.
Assuming your script is only going to be run from certain shells, and only with a little bit of flexibility required, you can probably relax some of this paranoia. It is still good to look at your options. There are common patterns that people use that are particularly problematic.
In particular, the FAQ recommends avoiding the very commonly used
$0
variable:As an alternative, you could use
$BASH_SOURCE
instead. Something like this:There are some caveats to this solution, too. Check out the FAQ page to see the trade-offs between different solutions. They seem to recommend
cd
in combination with$BASH_SOURCE
in cases where it will work for you, as you get a handy error condition when it fails to expand properly.See this: Bash: How _best_ to include other scripts?
I suggest to use:
Try the following: