bash 如何获取当前目录相对于git仓库根目录的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39922706/
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 the path of the current directory relative to root of the git repository?
提问by ewok
I've seen this question, which tells how to get the path of a particular file relative to the root of the git repo. But I now want to get the path of the current directory, not a specific file. If I use
我见过这个问题,它告诉我们如何获取特定文件相对于 git 存储库根目录的路径。但是我现在想获取当前目录的路径,而不是特定文件。如果我使用
git ls-tree --full-name --name-only HEAD .
I get the list of all the files in the directory.
我得到目录中所有文件的列表。
Is this possible?
这可能吗?
回答by Arkadiusz Drabczyk
How about:
怎么样:
$ git rev-parse --show-prefix
From man git-rev-parse
:
来自man git-rev-parse
:
--show-prefix
When the command is invoked from a subdirectory, show
the path of the current directory relative to the top-level
directory.
回答by Peter W
Adding onto the great answerfrom Arkadiusz Drabczyk, I just wrapped the suggested command in a shell script (calling it rd.sh, standing for "relative directory" or "repository directory"), and make it print "/" if the git rev-parse --show-prefix
command would return nothing (at the top level). I'm just starting to use this now, so we'll see how it works!
添加到Arkadiusz Drabczyk的出色答案中,我只是将建议的命令包装在一个 shell 脚本中(称为 rd.sh,代表“相对目录”或“存储库目录”),如果git rev-parse --show-prefix
命令可以,让它打印“/”不返回任何内容(在顶层)。我现在才开始使用它,所以我们将看看它是如何工作的!
#!/bin/bash
# rd.sh: shows the "repository directory" rather than the entire absolute dir from 'pwd'
RELATIVE_DIR=`git rev-parse --show-prefix`
if [ -z "$RELATIVE_DIR" ]; then
echo "/"
else
echo $RELATIVE_DIR
fi
回答by strobelight
#git ls-files --full-name | xargs -L1 dirname | sort -u
Use that git rev-parse --show-prefix
above, awesome
使用git rev-parse --show-prefix
上面的,真棒