【问题标题】:How to get the path of the current directory relative to root of the git repository?如何获取当前目录相对于 git 存储库根目录的路径?
【发布时间】:2017-02-16 18:36:48
【问题描述】:

我见过this question,它告诉我们如何获取特定文件相对于 git repo 根目录的路径。但我现在想获取当前目录的路径,而不是特定文件。如果我使用

git ls-tree --full-name --name-only HEAD .

我得到了目录中所有文件的列表。

这可能吗?

【问题讨论】:

  • 您是否正在寻找一种方法来读取路径?您是否有不想使用pwd 命令的原因?
  • @BrianaSwift 因为我想要相对于 git repo 根目录的路径,而不是机器上的绝对路径。例如,如果我有一个位于/home/ewok/git/repo 的仓库,而pwd 将打印/home/ewok/git/repo/src/java,我想要一个只给我/src/java 的命令

标签: git bash


【解决方案1】:
#git ls-files --full-name  | xargs -L1 dirname | sort -u

使用上面的git rev-parse --show-prefix,太棒了

【讨论】:

  • 这给了我当前目录,但也递归地给了我所有子目录
  • 其实这不太对。有时它给我当前目录,有时它只给我子目录。我不知道它什么时候给出了什么
  • 这样更好吗? git ls-files --full-name |头-1 | xargs -L1 目录名 |排序 -u
  • 不。现在它只给出了 1 个目录,但它给出的目录似乎并不一致。
  • git rev-parse --show-prefix 是我将放在工具带中的一个命令。
【解决方案2】:

怎么样:

$ git rev-parse --show-prefix

来自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.

【讨论】:

    【解决方案3】:

    添加到来自 Arkadiusz Drabczyk 的 great answer,我只是将建议的命令包装在一个 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
    

    【讨论】:

      猜你喜欢
      • 2013-06-01
      • 2015-04-07
      • 1970-01-01
      • 2015-08-22
      • 2017-09-30
      • 2014-04-14
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多