4

Suppose I have two lists:

lista="a b c d"
listb="e f"

I would like to write a function that returns the number of items on a given list:

>>foo $lista
4
>>foo $listb
2

I've tried using ${#<varname>[@]} syntax, also ${#!<varname>[@]}, unsuccessfully.

Thanks

Omer Dagan
  • 14,868
  • 16
  • 44
  • 60

3 Answers3

16

You can use wc -w for this:

$ lista="a b c d"
$ wc -w <<< "$lista"
4
$ listb="e f"
$ wc -w <<< "$listb"
2

From man wc:

-w, --words

print the word counts


To make it function, use:

list_length () {
        echo $(wc -w <<< "$@")
}

And then you can call it like:

list_length "a b c"
fedorqui
  • 275,237
  • 103
  • 548
  • 598
12

Put them into BASH array and look at array length.

a=($lista)
echo ${#a[@]}
4

a=($listb)
echo ${#a[@]}
2
anubhava
  • 761,203
  • 64
  • 569
  • 643
4

If you indeed want to write a function, you can take advantage of normal parameter parsing and the fact that $# contains the number of parameters passed:

 foo() { echo $#; }
mklement0
  • 382,024
  • 64
  • 607
  • 775