arrays - 从管道命令追加到数组变量

标签 arrays bash pipeline

我正在编写一个 bash 函数来获取所有 git 存储库,但是当我想将所有 git 存储库路径名存储到数组 patharray 时遇到了问题.这是代码:

gitrepo() {
    local opt

    declare -a patharray
    locate -b '\.git' | \
        while read pathname
        do
            pathname="$(dirname ${pathname})"
            if [[ "${pathname}" != *.* ]]; then
            # Note: how to add an element to an existing Bash Array
                patharray=("${patharray[@]}" '\n' "${pathname}")
                # echo -e ${patharray[@]}
            fi
        done
    echo -e ${patharray[@]}
}

我想将所有存储库路径保存到 patharray数组,但我无法在 pipeline 之外获取它由 locate 组成和 while命令。
但是我可以得到 pipeline 中的数组命令,注释命令# echo -e ${patharray[@]}如果未注释,效果很好,那么我该如何解决这个问题呢?

我试过 export命令,但是它似乎无法通过 patharray到管道。

最佳答案

Bash 在单独的 SubShell 中运行管道的所有命令秒。当包含 while 循环的子 shell 结束时,您对 patharray 变量所做的所有更改都将丢失。

您可以简单地将 while 循环和 echo 语句组合在一起,以便它们都包含在同一个子 shell 中:

gitrepo() {
    local pathname dir
    local -a patharray

    locate -b '\.git' | {                      # the grouping begins here
        while read pathname; do
            pathname=$(dirname "$pathname")
            if [[ "$pathname" != *.* ]]; then
                patharray+=( "$pathname" )     # add the element to the array
            fi
        done
        printf "%s\n" "${patharray[@]}"        # all those quotes are needed
    }                                          # the grouping ends here
}

或者,您可以将代码结构化为不需要管道:使用 ProcessSubstitution (有关详细信息,请参阅 Bash 手册 - man bash | less +/Process\Substitution):

gitrepo() {
    local pathname dir
    local -a patharray

    while read pathname; do
        pathname=$(dirname "$pathname")
        if [[ "$pathname" != *.* ]]; then
            patharray+=( "$pathname" )     # add the element to the array
        fi
    done < <(locate -b '\.git')

    printf "%s\n" "${patharray[@]}"        # all those quotes are needed
}

关于arrays - 从管道命令追加到数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229058/

相关文章:

javascript - 动态添加数组元素到 JSON 对象

bash [第二个参数 : command not found

python - python中的功能管道,如来自R's magrittr的%>%

jenkins - Jenkin 控制台输出在管道的开始和结束之间不打印任何内容

python - 如何将 boolean 掩码存储为 Cython 类的属性?

python - 在没有numpy的情况下更改对角线方阵 - Python

java - 将 ArrayList 转换为 DefaultListModel

linux - 日期和条件 bash 命令的奇怪但非常简单的问题

linux - 如何创建配置脚本?

c - 在 DSP 开发板上使用 C 语言流水线化一维卷积算法