gpt4 book ai didi

bash - 如何在 bash 的 while 循环中将条目附加到数组中?

转载 作者:行者123 更新时间:2023-12-03 03:51:01 25 4
gpt4 key购买 nike

当我在 bash 中声明一个数组时 $ ARRAY=('ele1' ele2') 我可以使用 $ ARRAY+=('ele3') 向其附加一个元素.

echo ${ARRAY[@]}
ele1 ele2 ele3

但是,在 while 循环中的脚本内我无法让它工作:

FOUNDFILES=$(ls -lA)
LINE_CNT=1
ARRAY=()

echo -e "$FOUNDFILES" | while read line
do
ARRAY+=("test")
LINE_CNT=$((LINE_CNT+1))
done

echo "${ARRAY[@]}"
echo $LINE_CNT

LINE_CNT 变量提供找到的文件数量,但我的数组仍为空。我做错了什么?

最佳答案

一些事情:

  1. 不要假设 find 每行只输出一个文件名;当文件名包含换行符时会中断。

  2. 不要假设 find 输出的换行符是输出中唯一的空格。

  3. 当使用 glob 时,根本不要使用 find


shopt -s globstar
foundfiles=(./**/"$1")

declare -a array
line_cnt=1
for f in "${foundfiles[@]}"; do
array+=(test)
line_count=$((line_count + 1))
done

如果您对 find 的调用比 glob 可以处理的更复杂,并且您的 find 版本可以输出以 null 分隔的文件名,请使用

# -d for readarray was introduced in bash 4.4; earlier versions
# require something more complex; see Gordan Davidson's answer at
# https://stackoverflow.com/a/1120952/1126841
readarray -t -d $'\0' < <(find . ... -name "$1" -print0)

如果您的 find 支持输出空分隔的文件名,请重新考虑在 bash 中编写此内容。 (您可以考虑使用 zsh,它具有一组极其丰富的 glob 功能,可以消除许多需要 find 的情况。)

关于bash - 如何在 bash 的 while 循环中将条目附加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59289355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com