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 #
?
Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression} . The strings and placeholders get passed to a function — either a default function, or a function you supply.
Shell is a UNIX term for the interactive user interface with an operating system. The shell is the layer of programming that understands and executes the commands a user enters. In some systems, the shell is called a command interpreter.
It's a space separated string of all arguments. For example, if $1 is "hello" and $2 is "world", then $* is "hello world".
$# represents the number of arguments. $* represents the string of arguments. $0 represents the name of the script itself. $?
• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.
#
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With