2

I have a following loop:

for chr in {1..3};
do
futureList="${variable1} ${variable2}"
done

I would like to modify it so that futureList appends new set of variables in each consecutive cycle. Expected outcome should look something like this:

echo $futureList

string1 string2, string3 string4, string5 string6 etc
0

2 Answers 2

2

This is good usecase to use arrays:

var1='string1'
var2='string2'

futureList=() # declare an array

for i in {1..5}; do
   futureList+=("$var1 $var2") # inside loop append value to array
done

# check array content
# decclare -p futureList
# or use printf
printf '%s\n' "${futureList[@]}"

string1 string2
string1 string2
string1 string2
string1 string2
string1 string2
Sign up to request clarification or add additional context in comments.

4 Comments

How does this match the desired output?
No, it's more the question asked to increment 'string[n]' and not just echo the strings 1...5 times
OP mentioned that futureList appends new set of variables in each consecutive cycle which obviously can be easily done inside the while loop to achieve whatever output.
Which isn't proper English when you compare his desired output
1

Here is how I would do it.

n=1
for chr in {1..3}; do
  array1+=("string$n") array2+=("string$((n+3))")
  ((n++))
done

Save the formatted output in the variable futurelist.

printf -v futurelist '%s %s, ' "${array1[@]}" "${array2[@]}"

Check the output

echo "$futurelist"

Output

string1 string2, string3 string4, string5 string6, 

I'm pretty sure someone will come up with more ways to do better.

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.