bash - 将数组与查找命令一起使用
bash - using array with find command
我想将找到的目录追加到数组中。
#!/bin/bash
FILES=()
find . ! \( \( -path './android/out' -o -path './.repo' \) -prune \) -type d -name prebuilts | while read file; do
echo "FILES -->$file"
FILES+=("$file")
done
echo "num of FILES: ${#FILES[@]}"
echo "FILES: ${FILES[@]}"
但结果如下:
FILES -->./android/test/vts/prebuilts
FILES -->./android/system/apex/shim/prebuilts
FILES -->./android/system/sepolicy/prebuilts
FILES -->./android/vendor/tvstorm/prebuilts
FILES -->./android/vendor/dmt/prebuilts
FILES -->./android/kernel/prebuilts
FILES -->./android/prebuilts
FILES -->./android/developers/build/prebuilts
FILES -->./android/external/selinux/prebuilts
FILES -->./android/development/vndk/tools/header-checker/tests/integration/version_script_example/prebuilts
num of FILES: 0
FILES:
为什么数组的num为0?
您正在 |
之后填充数组,即在子 shell 中。来自子 shell 的更改不会传播到父 shell。
改用进程替换:
while read file; do
echo "FILES -->$file"
FILES+=("$file")
done < <(find . ! \( \( -path './android/out' -o -path './.repo' \) -prune \) -type d -name prebuilts)
如果不需要作业控制,也可以shopt -s lastpipe
到运行当前shell管道中的最后一个命令。
我想将找到的目录追加到数组中。
#!/bin/bash
FILES=()
find . ! \( \( -path './android/out' -o -path './.repo' \) -prune \) -type d -name prebuilts | while read file; do
echo "FILES -->$file"
FILES+=("$file")
done
echo "num of FILES: ${#FILES[@]}"
echo "FILES: ${FILES[@]}"
但结果如下:
FILES -->./android/test/vts/prebuilts
FILES -->./android/system/apex/shim/prebuilts
FILES -->./android/system/sepolicy/prebuilts
FILES -->./android/vendor/tvstorm/prebuilts
FILES -->./android/vendor/dmt/prebuilts
FILES -->./android/kernel/prebuilts
FILES -->./android/prebuilts
FILES -->./android/developers/build/prebuilts
FILES -->./android/external/selinux/prebuilts
FILES -->./android/development/vndk/tools/header-checker/tests/integration/version_script_example/prebuilts
num of FILES: 0
FILES:
为什么数组的num为0?
您正在 |
之后填充数组,即在子 shell 中。来自子 shell 的更改不会传播到父 shell。
改用进程替换:
while read file; do
echo "FILES -->$file"
FILES+=("$file")
done < <(find . ! \( \( -path './android/out' -o -path './.repo' \) -prune \) -type d -name prebuilts)
如果不需要作业控制,也可以shopt -s lastpipe
到运行当前shell管道中的最后一个命令。