Linux 在 Bash 的文件路径参数中获取最后一个目录名/文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3294072/
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
Get last dirname/filename in a file path argument in Bash
提问by TJ L
I'm trying to write a post-commit hook for SVN, which is hosted on our development server. My goal is to try to automatically checkout a copy of the committed project to the directory where it is hosted on the server. However I need to be able to read only the last directory in the directory string passed to the script in order to checkout to the same sub-directory where our projects are hosted.
我正在尝试为 SVN 编写一个提交后挂钩,它托管在我们的开发服务器上。我的目标是尝试自动将已提交项目的副本签出到它在服务器上托管的目录。但是,我需要能够仅读取传递给脚本的目录字符串中的最后一个目录,以便签出到托管我们项目的同一子目录。
For example if I make an SVN commit to the project "example", my script gets "/usr/local/svn/repos/example" as its first argument. I need to get just "example" off the end of the string and then concat it with another string so I can checkout to "/server/root/example" and see the changes live immediately.
例如,如果我对项目“example”进行 SVN 提交,我的脚本将“/usr/local/svn/repos/example”作为它的第一个参数。我只需要从字符串的末尾取出“example”,然后将它与另一个字符串连接起来,这样我就可以结帐到“/server/root/example”并立即查看更改。
采纳答案by sth
回答by Paused until further notice.
Bash can get the last part of a path without having to call the external basename
:
Bash 可以获取路径的最后一部分而无需调用外部basename
:
subdir="/path/to/whatever/${1##*/}"
回答by Jingguo Yao
The following approach can be used to get any path of a pathname:
以下方法可用于获取路径名的任何路径:
some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))
Output:
输出:
c
b
a