0

I'm doing a bash script and I need to get the length of an array starting from an element.

Let's say that the array is:

array=(1 2 3 4 5) 

It is possible to print the array with an offset of 2 using:

echo ${array[@]:2} 3 4 5 

It is possible to print the length of the array using:

echo ${#array[@]} 5 

I tried printing the length of the array with an offset of 2 using:

echo ${#array[@]:2} 

It doesn't work, the expected result is:

3 

I have found a way to do it but I'm not sure if it's the best way:

echo $(( ${#array[@]} - 2 )) 3 

Is there a best way to do this?

Thanks!

    1 Answer 1

    0

    ${var:2} is also a substring expansion, it expands to the value of $var with the first two characters removed. With that in mind, ${#array[@]:2} seems a bit ambiguous, should it first pick the two elements off the array, then take the length; or should it first take the length and then take first two characters off that number?

    The latter is arguably silly, but then the first is also unnecessary as one can just what you did and subtract two from the full length of the array.

    For what it's worth, ksh doesn't support ${#array[@]:2} either. Since many of Bash's features are originally from ksh, it might also be why Bash doesn't support that. On the other hand, Zsh does process ${#array[@]:2}, it gives the length of the array minus 2 (so the 3 you expected in the example).

    2
    • So what is the best way to do it?
      – A.Lacasse
      CommentedSep 15, 2019 at 23:29
    • @A.Lacasse subtract the offset from ${#array[@]}, as you're doing in your final example.
      – cas
      CommentedSep 16, 2019 at 4:58

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.