How best to include other scripts?


The way you would normally include a script is with "source"




echo "The main script"

echo "The included script"

The output of executing "./" is:

The included script
The main script

... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path.

What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?

2/22/2019 1:28:02 AM

Accepted Answer

I tend to make my scripts all be relative to one another. That way I can use dirname:


my_dir="$(dirname "$0")"

5/31/2014 9:21:58 AM

I know I am late to the party, but this should work no matter how you start the script and uses builtins exclusively:

if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
. "$DIR/"
. "$DIR/"

. (dot) command is alias to source, $PWD is the Path for the Working Directory, BASH_SOURCE is an array variable whose members are the source filenames, ${string%substring} strips shortest match of $substring from back of $string

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow