user18429846
user18429846

Reputation:

Bash: Using Indexes of variables in loops

i currently have to programm a script that takes 3 variables and puts them together in all possible ways. I configured the variables in this way (replaced the actuall "domains" and "front", because i am not sure if i am allowed to reveal them...)

Domains=(".1" ".2" ".3" ".4" ".5")

Front=("1" "2" "3" "4" "5" "6" )

Numbers=({00001..00020})                        

To add the variables together i made this:

STR1="${Front[0]}${Numbers[0]}${Domains[0]}"

I now have the problem that i don't know how i can make a loop that creates all possible combinations.

In the end, all those combinations should be put behind the command "host" in the shell.

And just a question, is it possible to save all the combinations that had an IP-adress in an file? If the answer is yes, i would be very pleased if someone could help me out with that too....

Kind regards Elias

Upvotes: 0

Views: 30

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15313

That seems a lot of brute-force work, but...

First, do you really need the indexes?

for f in "${Front[@]}"; do 
  for n in "${Numbers[@]}"; do 
    for d in "${Domains[@]}"; do
      echo "$f$n$d"
    done
  done
done

If you do actually need the indexes -

for f in "${!Front[@]}"; do 
  for n in "${!Numbers[@]}"; do 
    for d in "${!Domains[@]}"; do
      echo ""${Front[f]}${Numbers[n]}${Domains[d]}""; 
    done; 
  done; 
done

If it's a big dataset, probably nicer to your resources to use counters, though it's a lot more maintenance.

f=0; n=0; d=0;
while (( f < ${#Front[@]} )); do
  while (( n < ${#Numbers[@]} )); do
    while (( d < ${#Domains[@]} )); do
      echo "${Front[f]}${Numbers[n]}${Domains[$((d++))]}";
    done;
    d=0; ((n++));
  done;
  n=0; ((f++))
done

Upvotes: 1

Related Questions