Can anyone spot where I'm going wrong when creating an array in bash?

61 Views Asked by At

I'm creating a shell script to find and delete screenshots saved on my desktop. I'm trying to use mapfile to create an array of file paths.

However I'm struggling to manage it as my current code creates an array that has only a single element!

Worth mentioning that the commented out code succeeds in creating the array I want (if I pretend the word splitting isn't happening). I know that it isn't ideal as it's splitting the output into separate array elements but at least it's creating an array with more than one element!

Can anyone point me in the right direction because I've been looking up example of how to use mapfile and no success yet :(

Code:

declare -a files

mapfile -d '' files < <(find "$HOME/Desktop" -maxdepth 1 -type f -name "*.png")

# files=($(find "$HOME/Desktop" -maxdepth 1 -type f -name *.png))

echo "${#files[@]}"

Screenshot of current code

1

There are 1 best solutions below

2
On

Thanks to @jordanm for spotting my mistake.

I needed to add the -print0 action to print the full file name followed by a null character as it was defaulting to print.

This is the corrected version without the unnecessary declare:

mapfile -d '' files < <(find "$HOME/Desktop" -maxdepth 1 -type f -name "*.png" -print0)