我正在编写一个 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/