3

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.