0

I tell Bash (v4.4) to give me an array, and I ask how long it is:

$ list=(one two three four)
$ echo ${#list}
3

Why are there so many more entries if I have - in some words?

$ list=(one-two three-four)
$ echo ${#list}
7

If I ask for the items, most of them are empty. All the ones with values are first, despite the (apparently) odd behavior with - in words.

$ for ix in $(seq 0 ${#list}); do
>     echo "- ${list[$ix]}"
> done
- one-two
- three-four
- 
- 
- 
- 
- 

What is going on?

Michael
  • 8,362
  • 6
  • 61
  • 88
  • `echo "${#list[@]}"` if you want to count array elements instead of the length of element 0. Or `declare -p list` to _see_ your array's contents and answer any question about how many elements there are. – Charles Duffy Feb 07 '22 at 19:10
  • 1
    Putting it a little differently: `$list` is identical to `${list[0]}`; you need to use `${list[@]}` to refer to something _as an array_. Thus, `${#list}` is the length of `${list[0]}`. – Charles Duffy Feb 07 '22 at 19:11

1 Answers1

2

"One-two" has seven characters. You find the length of the list array with echo ${#list[@]}.

echo ${#list} gives you the string length of the first list element. For Bash, i recommend the following cheatsheet: https://devhints.io/bash

typewriter
  • 338
  • 2
  • 8
  • OP, notice that even the first length check was wrong. It printed `3` for an array with `4` elements. – John Kugelman Feb 07 '22 at 19:05
  • @JohnKugelman Thanks. I just thought it was 0-indexed and printing the IX of the last item. Bad luck choosing "one" for the first element. – Michael Feb 07 '22 at 19:58