質問

I'm curious as to why the following:

array1=(file1 file2 file3)
array2=()
for i in ${array1[@]}
do
    find . -name $i -type f -print0 2>/dev/null | \
        while read -d '' -r file
        do
            array2+=( $file )
        done
done

fails to populate array2 assuming the filenames file1, file2, and file3 exist in the filesystem in sub-directories from the parent where the search is initiated. I would appreciate if someone could point out where I mis-stepped here.

役に立ちましたか?

解決

Try this:

array1=(file1 file2 file3)
array2=()
for i in "${array1[@]}"
do
        while read -d '' -r file
        do
            array2+=( "$file" )
        done < <(find . -name "$i" -type f -print0)
done

Due to your use of pipes sub shell is created and your array2 values get lost when sub shell ends.

他のヒント

If you are using bash 4, you can avoid using find:

shopt -s globstar
array1=(file1 file2 file3)
array2=()
for i in "${array1[@]}"
do
    for f in **/"$i"; do
        [[ -f "$f" ]] && array2+=( "$f" )
    done
done
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top