如何获取文件相对于Git存储库根的路径?
例如:如何获取文件相对于Git存储库根的路径?,git,path,Git,Path,例如: $ cd lib $ git absolute-path test.c # how to do this? lib/test.c 至少从git 1.6.0开始,使用: 对于较旧的git,请使用: 这只适用于已提交到repo中的文件,但总比没有好。将以下内容粘贴到bash终端将起作用,无论“test.c”当前是否存在。为了将来的方便,您可以将git绝对路径函数复制到.bashrc文件中 git-absolute-path () { fullpath=$([[ $1 = /* ]
$ cd lib
$ git absolute-path test.c # how to do this?
lib/test.c
至少从git 1.6.0开始,使用:
对于较旧的git,请使用:
这只适用于已提交到repo中的文件,但总比没有好。将以下内容粘贴到bash终端将起作用,无论“test.c”当前是否存在。为了将来的方便,您可以将git绝对路径函数复制到.bashrc文件中
git-absolute-path () {
fullpath=$([[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}")
gitroot="$(git rev-parse --show-toplevel)" || return 1
[[ "$fullpath" =~ "$gitroot" ]] && echo "${fullpath/$gitroot\//}"
}
git-absolute-path test.c
为了获取当前目录相对于git根目录的路径,我最后执行了以下操作:
if gitroot=$(git rev-parse --show-toplevel 2>/dev/null); then
directory=$(realpath --relative-to="$gitroot" .)
fi
(我假设是Bash,我不知道它的可移植性有多好。)MacOSX“readlink”没有-f(我假设是*BSD)。关于可移植方式的建议?“绝对路径”和“相对于回购协议”似乎相互矛盾?我必须使用通配符,否则找不到该文件,除非它位于回购协议的根目录中。使用$git ls文件--全名*测试。c@PedroGarcíaMedina我发布的两个命令都希望
test.c
是相对于当前工作目录的路径。因此,当您已经知道某个文件的位置,但希望将该路径转换为相对于repo根的“绝对”路径时,可以使用它们。如果您试图在整个repo中搜索名为test.c
的文件,我建议运行cd“$(git rev parse--show toplevel)”;git ls文件--全名'*/test.c''test.c'
。请注意引号,以防止shell插入星号。
git-absolute-path () {
fullpath=$([[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}")
gitroot="$(git rev-parse --show-toplevel)" || return 1
[[ "$fullpath" =~ "$gitroot" ]] && echo "${fullpath/$gitroot\//}"
}
git-absolute-path test.c
if gitroot=$(git rev-parse --show-toplevel 2>/dev/null); then
directory=$(realpath --relative-to="$gitroot" .)
fi