0

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?

8
  • @EtanReisner You lost the bet :D It returns []. Commented Jul 21, 2015 at 13:20
  • Songy deleted answer below was correct, it was my mistake, copied his solution wrong... DEVICES=( $(some|command) ) works just fine. Commented Jul 21, 2015 at 13:24
  • 1
    I'll undelete it then ;P Didn't want people doing the wrong thing :P Commented Jul 21, 2015 at 13:25
  • 1
    @m0skit0 No problem :P Was furiously typing into a terminal to figure out what it could be :P Commented Jul 21, 2015 at 13:27
  • 1
    @EtanReisner It doesn't matter, when you declare a variable then it automatically has an "array length" of 1. Try var="";echo "${#var[*]}" Commented Jul 21, 2015 at 13:28

1 Answer 1

3

You need to make DEVICES an array.

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

At the moment it is just a single string

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this both word-splits and expands globs/etc. So this isn't a generally safe pattern to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.