0

I have a function from a script that calls another script. I want to call it in a few other scripts which is in different directories.

[nir@dev nir]$ ll -R
.:
total 8
-rwxr-xr-x 1 nir nir 44 Jul  2 08:41 a.sh
drwxrwxr-x 2 nir nir 18 Jul  2 08:41 b
drwxrwxr-x 2 nir nir 20 Jul  2 08:42 lib
-rwxr-xr-x 1 nir nir 13 Jul  2 08:39 run_me.sh

./b:
total 4
-rwxr-xr-x 1 nir nir 45 Jul  2 08:41 a.sh

./lib:
total 4
-rwxr-xr-x 1 nir nir 46 Jul  2 08:42 lib.sh
[nir@dev nir]$ pwd
/tmp/nir
[nir@dev nir]$ cat run_me.sh
echo working
[nir@dev nir]$ cat lib/lib.sh
run_me(){

echo $(realpath $0)
./run_me.sh
}

[nir@dev nir]$ cat a.sh
cd ` dirname "$0" `

. ./lib/lib.sh

run_me
[nir@dev nir]$ cat b/a.sh
cd ` dirname "$0" `

. ../lib/lib.sh

run_me
[nir@dev nir]$ ./a.sh
/tmp/nir/a.sh
working
[nir@dev nir]$ ./b/a.sh
realpath: ‘./b/a.sh’: No such file or directory

../lib/lib.sh: line 4: ./run_me.sh: No such file or directory

Beside moving the function inside run_me.sh what are my option to fix it within lib.sh?

Nir
  • 2,497
  • 9
  • 42
  • 71
  • 1
    "cd ` dirname "$0" `" will break on spaces. Check your scripts with shellcheck – KamilCuk Jul 02 '21 at 09:25
  • In lib.sh, the path of its dependency run_me.sh shouldn't be based on the current working directory but rather on the location of the lib.sh script. See [this question](https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel) about how to reliably obtain it – Aaron Jul 02 '21 at 09:25

1 Answers1

1

are my option to fix it within lib.sh?

Call it relative to lib.sh. For example:

run_me() {
    "${BASH_SOURCE%/*}"/run_me.sh
}

You could also add the path to lib.sh to PATH and just let Bash serach for it.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111