Reputation: 1010
I know that one can get the length of an array in bash by doing ${#arrayname[@]}
.
My question is: is this just something that I have to memorize, or can this syntax be broken down into understandable parts? For instance, what does the @
symbol mean where one would expect to find the index? Why the #
?
Upvotes: 10
Views: 8312
Reputation: 63892
You should memorize. :) The #
usually means number. e.g. the
$#
- is the number of arguments${#str}
- length of the string $str
${#arr[@]}"
- length (number of elements) of the array arr
${#arr}
- the length of the 1st element of the array (like the str
above)Unfortunately the ${parameter#word}
or ${parameter##word}
has nothing with numbers. (it removes the shortest/longest word
from the beginning of the parameter
.
And also, the # ....
is comment ;)
Upvotes: 9
Reputation: 780724
#
at the beginning of a variable reference means to get the length of the variable's value. For a normal variable this means its length in characters. #
is the "number" sign, so you can remember this as meaning "the number of things in the variable".
@
or *
in an array index means to use the whole array, not a specific element, and instead of returning the number of characters, it returns the number of array elements. *
is used as a wildcard in many contexts, so this should be easy to remember. Also, $*
and $@
are used to mean all the arguments to a shell script, so the parallel with all the array elements should be obvious.
You can't just write ${#arrayname}
because when you use an array variable without a subscript, it's equivalent to element 0
of the array. So ${#arrayname}
is the same as ${#arrayname[0]}
, which is the number of characters in the first element of the array.
Upvotes: 20
Reputation: 85550
In general usage of form ${#PARAMETER}
returns the length in number of characters and NOT bytes of the parameter's value.
myString="Hello StackOverflow!"
printf "%s\n" "${#myString}"
20
But for arrays, this expansion type has two meanings:
@
and *
it
reports the number of set elements in the arrayConsider an example over arrays,
myArray=(1 2 3 4 15)
printf "%s\n" "${myArray[@]}" # <-- Gives me list of elements
1
2
3
4
15
printf "%s\n" "${#myArray[@]}" # <-- Gives me number of elements
5
It gets interesting now, the length of the last element 2
can be obtained by doing
printf "%s\n" "${#myArray[4]}"
2
Upvotes: 4
Reputation: 1041
The '@' acts the same way as '*'. Instead of providing a specific index this references the full thing.
The '#' is telling bash you want the length
https://www.cyberciti.biz/faq/finding-bash-shell-array-length-elements/
Upvotes: 1