【问题标题】:Getting the contents of a directory excluding everything inside .git in bash在 bash 中获取目录的内容,不包括 .git 中的所有内容
【发布时间】:2022-01-05 15:00:09
【问题描述】:

我需要获取作为 git 存储库的目录的内容数。

我必须得到:

1) Other directories inside the directory I am currently iterating (and the other sub-directories inside them if they exist)

2) .txt files inside the directory and its sub-directories

3) All the non-txt files inside the directory and its sub-directories

在上述所有情况下,我必须忽略 .git 目录,以及其中的所有文件和目录。

我还必须专门使用 bash 脚本。我无法使用其他编程语言。

现在我正在使用以下命令来实现这一点:

  1. 要获取我使用的所有.txt 文件:find . -type f \( -name "*.txt" \).git 中没有 .txt 文件,所以这是可行的。

  2. 要获取我使用的所有non-txt 文件:find . -type f \( ! -name "*.txt" \)。问题是我还从.git 获取了所有文件,我不知道如何忽略它们。

  3. 要获取所有directoriessub-directories,我使用:find . -type d。我不知道如何忽略.git 目录及其子目录

【问题讨论】:

    标签: bash git git-bash


    【解决方案1】:

    简单的方法是添加这些额外的测试:

    find . ! -path './.git/*' ! -path ./.git -type f -name '*.txt'
    

    问题在于 ./.git 仍然被遍历,这是不必要的,这需要时间。

    可以改为使用-prune-prune 不是测试(如 -path-type)。这是一个动作。操作是“如果是目录,则不要下降当前路径”。它必须与打印操作分开使用。

    # task 1
    find . -path './.git' -prune -o -type f -name '*.txt' -print
    
    # task 2
    find . -path './.git' -prune -o -type f ! -name '*.txt' -print
    
    # task 3
    find . -path './.git' -prune -o -type d -print
    
    • 如果未指定 -print./.git 也会作为默认操作打印。
    • 我使用了-path ./.git,因为你说的是​​“.git 目录”。如果由于某种原因在树中还有其他 .git 目录,它们被遍历和打印。要忽略树中名为.git所有 目录,请将-path ./.git 替换为-name .git

    【讨论】:

    • 非常感谢。它完美地工作。我只想问一个问题。当我使用find . -path './.git' -prune -o -type d -print 时,我得到一个. 目录。这是否代表当前目录?另外,如何在输出中忽略它?
    • @SimosNeopoulos 是的,我几乎要提到这一点。它是当前目录,用find . 指定。如果匹配,将包含此前缀。由于-type f,它在前两个中不匹配。你可以这样做:find . -mindepth 1 -path './.git' -prune -o -type d -printfind . -path './.git' -prune -o -type d ! -path . -print
    • 就我个人而言,我会使用-name .git -prune,因为Git 不会存储任何名为.git 的东西(出于安全原因),因此更简单的-name 测试与Git 所做的相匹配。但当然,任何一个都有效。
    【解决方案2】:

    有时写一个 bash 循环比写一个单行代码更清晰

    for f in $(find .); do
        if [[ -d $f && "$f" == "./.git" ]]; then
            echo "skipping dir $f";
        else
            echo "do something with $f";
        fi;
    done
    

    【讨论】:

    • 它不起作用。我运行了代码,但仍然得到所有 .git 文件和文件夹
    • 您必须更改我的示例以使其适合您的需求 - 您需要的所有组件都在那里......
    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2013-08-04
    • 2011-02-25
    相关资源
    最近更新 更多