简体   繁体   中英

bash - using array with find command

I want to append found directories to array.

#!/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[@]}"

but result as below:

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: 

Why does num of array is 0?

You are populating the array after |, ie in a subshell. Changes from the subshell don't propagate to the parent shell.

Use process substitution instead:

while read file; do
    echo "FILES -->$file"
    FILES+=("$file")
done < <(find . ! \( \( -path './android/out' -o -path './.repo' \) -prune \) -type d -name prebuilts)

If you don't need job control, you can also shopt -s lastpipe to run the last command in a pipeline in the current shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM