zhe*_*oli 5 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[@]}
}
Run Code Online (Sandbox Code Playgroud)
我想将所有存储库路径保存到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
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以构建不需要管道的代码:使用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
}
Run Code Online (Sandbox Code Playgroud)
首先,附加到数组变量最好使用array[${#array[*]}]="value"或 ,array+=("value1" "value2" "etc")除非您希望转换整个数组(您不希望这样做)。
现在,由于管道命令在子进程中运行,因此对管道命令内的变量所做的更改不会传播到其外部。有几个选项可以解决这个问题(大多数都列在Greg 的 BashFAQ/024中):
通过 stdout 传递结果
\0路径中的任何特殊字符都可以通过用作分隔符来可靠地处理(请参阅将 find . -print0 的输出捕获到 bash 数组中以读取\0- 分隔的列表)
locate -b0 '\.git' | while read -r -d '' pathname; do dirname -z "$pathname"; done
Run Code Online (Sandbox Code Playgroud)
或者简单地
locate -b0 '\.git' | xargs -0 dirname -z
Run Code Online (Sandbox Code Playgroud)避免在子进程中运行循环
完全避免管道
进程替换(一种特殊的、语法支持的 FIFO 情况,不需要手动清理;代码改编自Greg 的 BashFAQ/020):
i=0 #`unset i` will error on `i' usage if the `nounset` option is set
while IFS= read -r -d $'\0' file; do
patharray[i++]="$(dirname "$file")" # or however you want to process each file
done < <(locate -b0 '\.git')
Run Code Online (Sandbox Code Playgroud)使用lastpipe选项(Bash 4.2 中的新功能) - 不运行子进程中管道的最后一个命令(平庸:具有全局效果)