user3248772
user3248772

Reputation: 41

How to store values returned by a loop in an array in shell scripting?

In shell scripting, I have a loop with an if condition inside a for loop.

for i in val1 val2
do
    if ((condition)) then
        printf ...
    fi
done

This loop returns me correct output which is a list of numbers. However, I want to store these numbers in an array to use inside another loop. How do I do this?

I want to know how to store the values returned by printf statement in an array.

Upvotes: 3

Views: 2061

Answers (1)

Amit Sharma
Amit Sharma

Reputation: 6174

Here's the solution:

#!/bin/bash

data=() #declare an array outside the scope of loop
idx=0   #initialize a counter to zero
for i in {53..99} #some random number range
do
    data[idx]=`printf "number=%s\n" $i` #store data in array
    idx=$((idx+1)) #increment the counter
done
echo ${data[*]} #your result

What code does

  • creates and empty array
  • creates an index-counter for array
  • stores result of output printf command in array at corresponding index (the backquote tells interpreter to do that)

Upvotes: 2

Related Questions