This is my array:
$ ARRAY=(one two three)
How do I print the array so I have the output like: index i, element[i]
using the printf
or for
loop I use below
1,one
2,two
3,three
Some notes for my reference
1 way to print the array:
$ printf "%s\n" "${ARRAY[*]}"
one two three
2 way to print the array
$ printf "%s\n" "${ARRAY[@]}"
one
two
three
3 way to print the array
$ for elem in "${ARRAY[@]}"; do echo "$elem"; done
one
two
three
4 way to print the array
$ for elem in "${ARRAY[*]}"; do echo "$elem"; done
one two three
A nothe way to look at the array
$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'
To loop through indices of array in Bash, use the expression $ {!arr [@]} to get the indices and use For loop to iterate over these indices. In the following script, we take an array arr with three elements and iterate over the indices of this array.
Bash For loop is a statement that lets you iterate specific set of statements over series of words in a string, elements in a sequence, or elements in an array. Bash For Loop. Following are the topics, that we shall go through in this bash for loop tutorial. For Loop to iterate over elements of an array. Syntax. arr=( "element1" "element2" . .
We can use the special variables in BASH i.e @ to access all the elements in the array. Let’s look at the code: We can iterate over the array elements using the @ operator that gets all the elements in the array. Thus using the for loop we iterate over them one by one.
Here is an example loop that iterates through all numbers from 0 to 3: Starting from Bash 4, it is also possible to specify an increment when using ranges. The expression takes the following form: Here’s an example showing how to increment by 5: You can also use the for loop to iterate over an array of elements.
You can iterate over the indices of the array, i.e. from 0
to ${#array[@]} - 1
.
#!/usr/bin/bash
array=(one two three)
# ${#array[@]} is the number of elements in the array
for ((i = 0; i < ${#array[@]}; ++i)); do
# bash arrays are 0-indexed
position=$(( $i + 1 ))
echo "$position,${array[$i]}"
done
Output
1,one
2,two
3,three
The simplest way to iterate seems to be:
#!/usr/bin/bash
array=(one two three)
# ${!array[@]} is the list of all the indexes set in the array
for i in ${!array[@]}; do
echo "$i, ${array[$i]}"
done
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