m0skit0
m0skit0

Reputation: 25863

Array variable shows wrong command result length when no results

I want to execute a command, store the result in an array, and know its size. The problem is that when I assign the command result to an array, it will show size 1 even if the command returned no results.

DEVICES=$(some|command)
echo "${#DEVICES[*]}" # Prints 1

However, if I do it manually, it works fine:

a=0
for i in $(some|command);
do
    a=$((a + 1))
done
echo "$a" # Prints 0

How can I assign the result to a variable and have the correct length?

Upvotes: 0

Views: 192

Answers (1)

Songy
Songy

Reputation: 851

You need to make DEVICES an array.

Change DEVICES=$(some|command) to DEVICES=( $(some|command) )

At the moment it is just a single string

Upvotes: 3

Related Questions