how to count the length of an array defined in bash? – Unix & Linux Stack Exchange
Posted by jpluimers on 2020/06/16
I needed to enumerate all the parameters to a function and access many of them by index in the same function, so thanks to both these:
- [WayBack] how to count the length of an array defined in bash? – Unix & Linux Stack Exchange
- [WayBack] bash – access element of $* (or $@) by index – Stack Overflow
I got at this:
declare -a arguments=("$@")
for index in ${!arguments[@]}; do
echo $index/${#arguments[@]}:${arguments[$index]}
done
These are all forms of Array handling or Shell Parameter Expansion with special cases for array variables:
!does indirection, in this case from the array to the index of the array#gets the lengt of the parameter (for arrays: the number of elements)[]acccesse an array variable using an index
Via:
- [WayBack] Bash Reference Manual: Shell Parameter Expansion
- [WayBack] Bash Reference Manual: Arrays
- [WayBack] bash – variable expansion in curly braces – Stack Overflow
- [WayBack] Variable substitution with an exclamation mark in bash – Unix & Linux Stack Exchange
- [WayBack] shell – BASH scripting: n-th parameter of $@ when the index is a variable? – Stack Overflow
- [WayBack] BashFAQ/006 – Greg’s Wiki: How can I use variable variables (indirect variables, pointers, references) or associative arrays?
–jeroen






Leave a comment