bashshellrelative-pathrealpath

relative path with lib in bash


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?


Solution

  • 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.