LHWizard
LHWizard

Reputation: 2379

bash array count always returns 1

I searched all over for this, but the terms are apparently too general. I'm writing a script to search a group of folders for .mp3 files. Some folders don't have mp3's so they have to be excluded.

I created an array to hold the uniq'd folder names. This find command will get the folders I need.

Folders=$(sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u)

When I try to count the number of folders in the array, I always get 1

echo ${#Folders[@]}

echo ${Folders[@]} prints them out on separate lines so I thought they were separate array elements. Can anyone explain what is going on? You might have to jiggle the field number in the cut command to reproduce locally.

Upvotes: 11

Views: 5276

Answers (3)

chepner
chepner

Reputation: 530872

Assuming bash 4 or later, don't use find here; use the globstar operator.

shopt -s globstar
folders=( /my/music/**/*.mp3 )

Also assuming that cut -d/ -f7 is supposed to extract the filename alone, follow this up with

folders=${folders[@]##*/}

Other methods for populating the array must take more care to accomodate files containing whitespace or characters like ?, *, or [. File names containing newlines (rare, but not illegal) are much more difficult to handle correctly. Pathname expansion is done inside the shell, so you don't need to worry about any such special characters.

Upvotes: 0

sjsam
sjsam

Reputation: 21955

Or do :

sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u | wc -l

Note

  • wc -l prints the number of lines which in this case would be the number of unique files
  • to make things a bit more explicit, use -printf "%p\n" option with find where %p specifier prints the file with full path.

Upvotes: 0

heemayl
heemayl

Reputation: 41987

Folders is not an array but a variable.

You need:

Folders=( $(sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u) )

i.e. enclose the command substitution with (). Now ${#Folders[@]} would give you the number of elements of array Folders.

Upvotes: 17

Related Questions