How do I define an array in a bash shell script? How do I find out bash array length (number of elements) while running a script using for shell loop?
Bash provides one-dimensional array variables. Any variable may be used as an array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. This page shows how to find number of elements in bash array.
How do I define bash array?
Array can be defined using following syntax:
ArrayName=("element 1" "element 2" "element 3")
Define array called distro with 3 elements, enter:
distro=("redhat" "debian" "gentoo") |
distro=("redhat" "debian" "gentoo")
How do I reference any element in bash array?
Any element of an array may be referenced using following syntax:
${ArrayName[subscript]}
|
${ArrayName[subscript]}
To print redhat i.e first element enter:
echo "${distro[0]}" echo "${distro[2]}" # will print gentoo |
echo "${distro[0]}"
echo "${distro[2]}" # will print gentoo
How do I find out bash shell array length?
You can easily find out bash shell array length using following syntax:
${#ArrayName[@]}
|
${#ArrayName[@]}
To print distro array length enter:
echo "${#distro[@]}" |
echo "${#distro[@]}"
Sample output:
3
If subscript is @ or *, the word expands to all members of name. By prefixing # to variable you will find length of an array (i.e number of elements). Now we can use bash for loop to read or print values from $distro:
## define it distro=("redhat" "debian" "gentoo") ## get length of $distro array len=${#distro[@]} ## Use bash for loop for (( i=0; i<$len; i++ )); do echo "${distro[$i]}" ; done |
## define it
distro=("redhat" "debian" "gentoo") ## get length of $distro array
len=${#distro[@]} ## Use bash for loop
for (( i=0; i<$len; i++ )); do echo "${distro[$i]}" ; done
Putting it all together
A sample shell script to print array called NAMESERVERS:
#!/bin/bash # define array # name server names FQDN NAMESERVERS=("ns1.nixcraft.net." "ns2.nixcraft.net." "ns3.nixcraft.net.") # get length of an array tLen=${#NAMESERVERS[@]} # use for loop read all nameservers for (( i=0; i<${tLen}; i++ )); do echo ${NAMESERVERS[$i]} done |
#!/bin/bash
# define array
# name server names FQDN
NAMESERVERS=("ns1.nixcraft.net." "ns2.nixcraft.net." "ns3.nixcraft.net.") # get length of an array
tLen=${#NAMESERVERS[@]} # use for loop read all nameservers
for (( i=0; i<${tLen}; i++ ));
do
echo ${NAMESERVERS[$i]}
done
Sample output:
ns1.nixcraft.net. ns2.nixcraft.net. ns3.nixcraft.net.
(adsbygoogle = window.adsbygoogle || []).push({});