bash 中 lib 的相对路径

relative path with lib in bash

我有一个脚本调用另一个脚本的函数。 我想在不同目录中的其他几个脚本中调用它。

[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 [=11=])
./run_me.sh
}

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

. ./lib/lib.sh

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

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

除了将函数移到 run_me.sh 中,我还有什么选择可以在 lib.sh 中修复它?

are my option to fix it within lib.sh?

相对于 lib.sh 调用它。例如:

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

您还可以将 lib.sh 的路径添加到 PATH 并让 Bash 搜索它。