Mercurial有一种打印根目录(包含.hg)的方法

hg root

git中是否有等价的东西来获取包含.git目录的目录?


当前回答

以防万一,如果您要将此路径提供给Git本身,请使用:/

# this adds the whole working tree from any directory in the repo
git add :/

# and is equal to
git add $(git rev-parse --show-toplevel)

其他回答

正如其他人所注意到的,解决方案的核心是使用git rev-parse——show-cdup。然而,也有一些边缘情况需要解决:

When the cwd already is the root of the working tree, the command yields an empty string. Actually it produces an empty line, but command substitution strip off the trailing line break. The final result is an empty string. Most answers suggest prepending the output with ./ so that an empty output becomes "./" before it is fed to cd. When GIT_WORK_TREE is set to a location that is not the parent of the cwd, the output may be an absolute pathname. Prepending ./ is wrong in this situation. If a ./ is prepended to an absolute path, it becomes a relative path (and they only refer to the same location if the cwd is the root directory of the system). The output may contain whitespace. This really only applies in the second case, but it has an easy fix: use double quotes around the command substitution (and any subsequent uses of the value).

正如其他答案所指出的,我们可以做cd”。/$(git rev-parse——show-cdup))”,但这会在第二个边缘大小写中中断(如果去掉双引号,则会在第三个边缘大小写中中断)。

许多shell将cd ""视为无操作,因此对于这些shell,我们可以执行cd "$(git rev-parse——show-cdup)"(双引号保护第一个边大小写中的空字符串作为参数,并在第三个边大小写中保留空白)。POSIX说cd ""的结果是未指定的,所以最好避免做这种假设。

在上述所有情况下工作的解决方案需要某种类型的测试。显式完成后,它可能是这样的:

cdup="$(git rev-parse --show-cdup)" && test -n "$cdup" && cd "$cdup"

第一个边不做cd操作。

如果运行cd可以接受。对于第一个边情况,则条件可以在参数展开中执行:

cdup="$(git rev-parse --show-cdup)" && cd "${cdup:-.}"

不管你是在git子目录下,还是在顶层,这个shell别名都有效:

alias gr='[ ! -z `git rev-parse --show-toplevel` ] && cd `git rev-parse --show-toplevel || pwd`'

更新为使用现代语法而不是反撇号:

alias gr='[ ! -z $(git rev-parse --show-toplevel) ] && cd $(git rev-parse --show-toplevel || pwd)'

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

git-config的手册页(在Alias下)说:

如果别名展开以感叹号作为前缀,则它将被视为外壳 命令。[…注意shell 命令将从存储库的顶级目录执行,这可能不是 必须是当前目录。

在UNIX上,你可以这样做:

git config --global --add alias.root '!pwd'

在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)(将当前目录更改为工作树的顶层。)