Let us say I have the following script files:
~/src/setup.sh::
#!/usr/bin/env bash
dn=$( dirname "$0" )
source "$dn/init/init.sh"
~/src/init/init.sh:
#!/usr/bin/env bash
dn=$( dirname "$0" )
source "$dn/start.sh"
start_servers "param1" "param2"
~/src/init/start.sh:
#!/usr/bin/env bash
start_servers() {
# ...
printf "start the servers..."
# ...
}
Sourcing the second file (start.sh) results that:
$ ./setup.sh
./init/init.sh: line 4: ./start.sh: No such file or directory
./init/init.sh: line 6: start_servers: command not found
Since I execute the setup.sh from .
, after sourcing the files, start.sh seems to be sourced from .
as well but I would like to source it from its proper location.
Any idea how to fix it? Thanks in advance.
Bash has the built-in $BASH_SOURCE
variable, which is similar to $0
, but - unlike the latter - correctly reflects the name of the running script even when sourced.
Thus, simply replacing $0
with $BASH_SOURCE
in your scripts should be enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With