bash get list length when list name is not fixed
bash
Solution
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"
Problem
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