Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I source multiple bash scripts into each others properly?

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.

like image 223
Mark Avatar asked Sep 06 '25 02:09

Mark


1 Answers

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.

like image 97
mklement0 Avatar answered Sep 07 '25 21:09

mklement0