如何在 Linux shell 脚本的命令行上从“../”获取完整路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7877768/
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 full path from "../" on command line in Linux shell script
提问by Rob Segal
If I have a shell script where I get the parent folder using "../" can I expand that out somehow into it's absolute path?
如果我有一个 shell 脚本,我可以在其中使用“../”获取父文件夹,我可以以某种方式将其扩展为绝对路径吗?
采纳答案by Ignacio Vazquez-Abrams
You want readlink -f
.
你要readlink -f
。
$ cd /tmp
$ readlink -f ..
/
回答by Andrey Tatarinov
Use realpath
用 realpath
$ realpath ..
/home
回答by Howard Abrams
While you can often get the full path of a directory using stat
, you can also use pwd -P
... however, it isn't much help unless you actually cd
to the directory you are interested in.
虽然您通常可以使用 获取目录的完整路径stat
,但您也可以使用pwd -P
... 但是,除非您确实cd
访问了您感兴趣的目录,否则它没有多大帮助。
To get around this limitation without actually changing the current working directory, I've found it fine to just run that cd
in a sub-shell, as in:
为了在不实际更改当前工作目录的情况下绕过此限制,我发现只需cd
在sub-shell 中运行它就可以了,如下所示:
THIS=`dirname dirname $(pwd)
` # Which is often "."
PARENT=$(
cd $THIS # At this point, we are sure we're in script's directory
dirname `pwd -P`
)
echo "PARENT=$PARENT"
回答by Alex.Li
When using in cmd line:
在 cmd 行中使用时:
PROJ_DIR=$(dirname $(pwd))
When using in shell script:
在 shell 脚本中使用时:
##代码##