Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash + for loop + output index number and element

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")'
like image 948
HattrickNZ Avatar asked Jul 27 '16 02:07

HattrickNZ


People also ask

How to loop through indices of array in Bash?

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.

How to use for loop in Bash?

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" . .

How to access all the elements in an array in Bash?

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.

How to iterate through an array of numbers in Bash?

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.


2 Answers

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
like image 110
xxfelixxx Avatar answered Nov 04 '22 06:11

xxfelixxx


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
like image 26
LegZ Avatar answered Nov 04 '22 06:11

LegZ