Home > Software engineering >  How to loop through an array in bash?
How to loop through an array in bash?

Time:10-12

i'm trying to loop through an array, I have two input values and I am trying to get one value to print in val1 and the second value in val2.So I had to make a text file called test_inputs.txt which has all the inputs that I need to print

This is the text file test_inputs.txt

1,2
3,4
10,30

I already know how to put the inputs in the array but I am having trouble printing the values. So far I have this

//this reads the text file and puts it in an array
IFS=,$'\n' read -d '' -r -a array < test_inputs.txt

for i in "${array[@]}"
do 
echo "val1: ${array[$i}} and val2: ${array[$i  ]}"
done

The desired output is

val1: 1 and val2: 2
val1: 3 and val2: 4
val1: 10 and val2: 30

CodePudding user response:

You can use a C-style for loop:

#!/bin/bash

IFS=,$'\n' read -d '' -r -a array < test_inputs.txt
n=${#array[*]}
for ((i = 0; i < n; i  = 2))
do 
    echo "val1: ${array[i]} and val2: ${array[i 1]}"
done

CodePudding user response:

I understand your question in that each line contains 2 entries, separated by a comma.

I suggest in this case to read the array line by line, instead by element:

mapfile <test_inputs.txt
for line in "${MAPFILE[@]}"
do
  echo "val1: ${line%,*} and val2: ${line#*,}"
done
  • Related