你如何在 Bash 中规范化文件路径? [英] How do you normalize a file path in Bash?
本文介绍了你如何在 Bash 中规范化文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想把 /foo/bar/..
转换成 /foo
是否有执行此操作的 bash 命令?
Is there a bash command which does this?
在我的实际案例中,该目录确实存在.
in my practical case, the directory does exist.
推荐答案
如果你想从路径中截取文件名的一部分,"dirname" 和 "basename" 是你的朋友,"realpath" 也很方便.
if you're wanting to chomp part of a filename from the path, "dirname" and "basename" are your friends, and "realpath" is handy too.
dirname /foo/bar/baz
# /foo/bar
basename /foo/bar/baz
# baz
dirname $( dirname /foo/bar/baz )
# /foo
realpath ../foo
# ../foo: No such file or directory
realpath /tmp/../tmp/../tmp
# /tmp
realpath
替代方案
如果你的shell不支持realpath
,你可以试试
If realpath
is not supported by your shell, you can try
readlink -f /path/here/..
还有
readlink -m /path/there/../../
工作原理与
realpath -s /path/here/../../
因为路径不需要存在来规范化.
in that the path doesn't need to exist to be normalized.
这篇关于你如何在 Bash 中规范化文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文