catalin
catalin

Reputation: 1116

bash store output of command in array

I'm trying to find if the output of the following command, stores just one file in the array array_a

array_a = $(find /path/dir1 -maxdepth 1 -name file_orders?.csv)
echo $array_a
/path/dir1/file_orders1.csv /path/dir1/file_orders2.csv
echo ${#array_a[@]}
1

So it tell's me there's just one element, but obviously there are 2. If I type echo ${array_a[0]} it doesn't return me anything. It's like, the variable array_a isn't an array at all. How can i force it to store the elements in array?

Upvotes: 0

Views: 1663

Answers (1)

tripleee
tripleee

Reputation: 189387

You are lacking the parentheses which define an array. But the fundamental problem is that running find inside backticks will split on whitespace, so if any matching file could contain a space, it will produce more than one element in the resulting array.

With -maxdepth 1 anyway, just use the shell's globbing facilities instead; you don't need find at all.

 array_a=(/path/dir1/file_orders?.csv)

Also pay attention to quotes when using the array.

 echo "${array_a[@]}"

Without the quotes, the whitespace splitting will happen again.

Upvotes: 3

Related Questions