Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash array count always returns 1

Tags:

arrays

bash

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.

like image 577
LHWizard Avatar asked Jan 05 '23 15:01

LHWizard


1 Answers

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.

like image 124
heemayl Avatar answered Jan 13 '23 22:01

heemayl