符号链接源文件的搜索路径

符号链接源文件的搜索路径

我有一个主脚本,它在同一文件夹中获取一个 bash 文件:

 $ cd
 $ mkdir mysrc && cd mysrc
 $ echo -e 'MY_LIB_NB=123987' > mylib.sh
 $ echo -e '#!/usr/bin/env bash\nsource mylib.sh\necho "My lib number: $MY_LIB_NB"\necho "I am in $(pwd) and I am running script $(readlink -f $0)"' > myscript.sh
 $ chmod +x myscript.sh
 $ ./myscript.sh
 My lib number: 123987
 I am in /home/me/mysrc and I am running script /home/me/mysrc/myscript.sh

到目前为止一切顺利。现在我将脚本符号链接到 bin 文件夹并从那里运行它:

$ mkdir bin
$ ln -s $HOME/mysrc/myscript.sh $HOME/mysrc/bin/myscript
$ cd bin
$ ./myscript
./myscript: line 2: mylib.sh: No such file or directory
My lib number: 
I am in /home/me/mysrc/bin and I am running script /home/me/mysrc/myscript.sh

我希望我的原始脚本能够获取位于其文件夹中的源文件。有没有一种简单的方法可以做到这一点,而不必明确提供库文件的绝对路径?

答案1

这个 bsh 脚本片段应该有帮助

# get the path to the currently running script:
self=$0 

# test if $self is a symlink:
if [ -L $self ] ; then 
  # readlink returns the path to the file the link points to:
  target=`readlink $self` 
else
  target=$self
fi

# strip off the script name from the path:
path=`dirname $target` 

# $path/mylib.sh now points to the mylib.sh 
# file in the folder where the original script is:
source $path/mylib.sh 

http://man7.org/linux/man-pages/man1/readlink.1.html

http://man7.org/linux/man-pages/man1/dirname.1.html

相关内容