The problem
Let’s say we have two scripts, /foo/bar/utils.sh
1 2 3 |
function do_something_useful { echo "Hello $1" } |
and script /foo/bar/main.sh
, in which you want to use function do_something_useful
from utils.sh
.
The common incorrect answer
You can easily bump into following answer on the internet:
1 2 3 4 5 |
#!/bin/bash source ./utils.sh do_something_useful "foobar" |
Which however doesn’t work unless you your shell’s current working path is the same as path to a directory where the script is located. But – if your working path is /foo,
and you run ./bar/main.sh
you just receive error message
1 |
./bar/foo/first.sh: line 5: do_something_useful: command not found |
The correct solution
The solution is simple.
1 2 3 4 5 |
#!/bin/bash source $(dirname "$0")/second.sh do_something_useful "foobar" |
Now even if you cd
into different directory, it still works. Sequence of commands
1 2 |
cd /foo ./bar/main.sh |
runs with no error and prints message Hello foobar