Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
当前回答
要计算当前git根目录的绝对路径,比如在shell脚本中使用,使用readlink和git rev-parse的组合:
gitroot=$(readlink -f ./$(git rev-parse --show-cdup))
Git-rev-parse——show-cdup给出正确的“..”’s to get 从你的cwd到根目录,如果你在根目录,则返回空字符串。 然后“prepend”。/"来处理空字符串大小写并使用 Readlink -f转换为完整路径。
你也可以在PATH中创建一个git-root命令作为shell脚本来应用这个技术:
cat > ~/bin/git-root << EOF
#!/bin/sh -e
cdup=$(git rev-parse --show-cdup)
exec readlink -f ./$cdup
EOF
chmod 755 ~/bin/git-root
(上面的代码可以粘贴到终端中创建git-root并设置执行位;实际的脚本在第2、3和4行。)
然后你可以运行git root来获得当前树的根。 注意,在shell脚本中,使用“-e”使shell在rev-parse失败时退出,这样如果不在git目录中,就可以正确地获得退出状态和错误消息。
其他回答
下面是我编写的处理这两种情况的脚本:1)带工作区的存储库,2)裸存储库。
https://gist.github.com/jdsumsion/6282953
Git-root(可执行文件在你的路径):
#!/bin/bash
GIT_DIR=`git rev-parse --git-dir` &&
(
if [ `basename $GIT_DIR` = ".git" ]; then
# handle normal git repos (with a .git dir)
cd $GIT_DIR/..
else
# handle bare git repos (the repo IS a xxx.git dir)
cd $GIT_DIR
fi
pwd
)
希望这对你们有帮助。
——show- topllevel是最近才添加到git rev-parse的吗?为什么没有人提到它?
从git rev-parse手册页:
--show-toplevel
Show the absolute path of the top-level directory.
在Shell框架中预先配置的Shell别名
如果你使用shell框架,可能已经有一个可用的shell别名:
$ GRT in oh-my-zsh (68k) (cd $(git rev-parse——show-toplevel || echo ".")) $ git-root in prezto (8.8k)(显示工作树根的路径) $ g . .Zimfw (1k)(将当前目录更改为工作树的顶层。)
我想进一步阐述丹尼尔·布罗克曼的精彩评论。
定义git配置全局别名。exec”!Exec '允许你做像git Exec make这样的事情,因为man git-config说:
如果别名展开以感叹号作为前缀,则它将被视为shell命令。[…注意,shell命令将从存储库的顶级目录执行,而不一定是当前目录。
知道$GIT_PREFIX将是相对于存储库的顶级目录的当前目录的路径也很方便。但是,知道这只是战斗的一半。Shell变量展开使得它很难使用。所以我建议像这样使用bash -c:
git exec bash -c 'ls -l $GIT_PREFIX'
其他命令包括:
git exec pwd
git exec make
git-extras
添加$ git根目录 看到https://github.com/tj/git-extras/blob/master/Commands.md git-root
$ pwd
.../very-deep-from-root-directory
$ cd `git root`
$ git add . && git commit
git-extra的可用性
Homebrew (osx)/linuxbrew(linux) $ brew安装git-extras Debian /ubuntu repos (https://packages.debian.org/sid/git-extras) $ apt-get安装git-extras