Is there a way to get the git root directory in one command?

前端 未结 22 1380
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 09:57

Mercurial has a way of printing the root directory (that contains .hg) via

hg root

Is there something equivalent in git to get the director

22条回答
  •  面向向阳花
    2020-11-22 10:47

    To calculate the absolute path of the current git root directory, say for use in a shell script, use this combination of readlink and git rev-parse:

    gitroot=$(readlink -f ./$(git rev-parse --show-cdup))
    

    git-rev-parse --show-cdup gives you the right number of ".."s to get to the root from your cwd, or the empty string if you are at the root. Then prepend "./" to deal with the empty string case and use readlink -f to translate to a full path.

    You could also create a git-root command in your PATH as a shell script to apply this technique:

    cat > ~/bin/git-root << EOF
    #!/bin/sh -e
    cdup=$(git rev-parse --show-cdup)
    exec readlink -f ./$cdup
    EOF
    chmod 755 ~/bin/git-root
    

    (The above can be pasted into a terminal to create git-root and set execute bits; the actual script is in lines 2, 3 and 4.)

    And then you'd be able to run git root to get the root of your current tree. Note that in the shell script, use "-e" to cause the shell to exit if the rev-parse fails so that you can properly get the exit status and error message if you are not in a git directory.

提交回复
热议问题