bash 通过符号链接调用时如何获取脚本本身内部的脚本文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/920755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get script file path inside script itself when called through sym link
提问by Ma99uS
When I need to get path to the script file inside script itself I use something like this:
当我需要在脚本本身中获取脚本文件的路径时,我使用如下内容:
`dirname if [ -L readlink -f "Dir=$(dirname $(readlink -f "dirname $(realpath skaerst@test01-centos7:~/Documents> ../test/path.sh
dirname realpath: /home/skaerst/test
skaerst@test01-centos7:~/Documents> cat ../test/path.sh
#!/bin/bash
echo "dirname realpath: $(dirname $(realpath skaerst@test01-centos7:~/Documents> ln -s ../test/path.sh p
skaerst@test01-centos7:~/Documents> ./p
dirname realpath: /home/skaerst/test
))"
)
"))
"
] ; then
DIR=$(dirname $(readlink -f skaerst@test01-centos7:~/Documents> rpm -qf $(which realpath) $(which dirname)
coreutils-8.22-15.el7_2.1.x86_64
coreutils-8.22-15.el7_2.1.x86_64
)) ;
else
DIR=$(dirname ##代码##) ;
fi ;
`
that works file until I call the script through sym link to it. In that case above code prints the location of the link instead the original file.
在我通过符号链接调用脚本之前,该文件一直有效。在这种情况下,上面的代码打印链接的位置而不是原始文件。
Is there a way to get the path of the original script file, not the link?
有没有办法获取原始脚本文件的路径,而不是链接?
Thanks, Mike
谢谢,迈克
回答by dsm
回答by lhunath
You reallyneed to read the following BashFAQ article:
您确实需要阅读以下 BashFAQ 文章:
The truth is, the $0hacks are NOT reliable, and they will fail whenever applications are started with a zeroth argument that is not the application's path. For example, login(1)will put a -in front of your application name in $0, causing breakage, and whenever you invoke an application that's in PATH$0won't contain the path to your application but just the filename, which means you can't extract any location information out of it. There are a LOT more ways in which this can fail.
事实是,$0hacks 并不可靠,只要应用程序以不是应用程序路径的第零个参数启动,它们就会失败。例如,login(1)将-在您的应用程序名称前面放置一个$0,导致损坏,并且每当您调用一个应用程序时,该应用程序PATH$0将不包含您的应用程序的路径,而只包含文件名,这意味着您无法提取任何位置信息其中。还有很多方法可能会失败。
Bottom line: Don't rely on the hack, the truth is you cannotfigure out where your script is, so use a configuration option to set the directory of your config files or whatever you need the script's path for.
底线:不要依赖 hack,事实是你无法弄清楚你的脚本在哪里,所以使用配置选项来设置你的配置文件的目录或任何你需要的脚本路径。
回答by Marius Dalacu
回答by StefanKaerst
I suggest this one:
我推荐这个:
##代码##example:
例子:
##代码##works with symlinks too because realpath uses -P by default:
也可以使用符号链接,因为 realpath 默认使用 -P:
##代码##realpath is available with coreutils >8.5, I guess
realpath 可用于 coreutils >8.5,我猜
##代码##hth
第
Regards
问候
Stefan
斯蒂芬

