fdfdfd
fdfdfd

Reputation: 501

Create a loop for 3 different variables to output all possible combinations

So lets say i have 3 lines of code

ABC
123
!@#

How do i create a for loop to output the number of ways to piece them together?

E.G ABC123!@#, ABC!@#123, 123ABC!@#$

here is my current line of code

 #!/bin/bash



    alphabet='ABC' numbers='123' special='!@#'

 for name in $alphabet$numbers$special 
  do   
  echo $name 
  done  
  echo  done

Upvotes: 2

Views: 262

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84559

You can also do it without a loop at all using brace expansion (but you lose the ability to exclude, e.g. ABCABCABC). For example:

#!/bin/bash

alpha='ABC'
num='123'
spec='!@#'

printf "%s\n" {$alpha,$num,$spec}{$alpha,$num,$spec}{$alpha,$num,$spec}

Example Use/Output

$ bash permute_brace_exp.sh
ABCABCABC
ABCABC123
ABCABC!@#
ABC123ABC
ABC123123
ABC123!@#
ABC!@#ABC
ABC!@#123
ABC!@#!@#
123ABCABC
123ABC123
123ABC!@#
123123ABC
123123123
123123!@#
123!@#ABC
123!@#123
123!@#!@#
!@#ABCABC
!@#ABC123
!@#ABC!@#
!@#123ABC
!@#123123
!@#123!@#
!@#!@#ABC
!@#!@#123
!@#!@#!@#

Upvotes: 1

tso
tso

Reputation: 4924

alphabet='ABC' numbers='123' special='!@#'

for name1 in $alphabet $numbers $special 
#on 1st iteration, name1's value will be ABC, 2nd 123 ...
do
    for name2 in $alphabet $numbers $special
    do
        for name3 in $alphabet $numbers $special
        do
            #here we ensure that we want strings only as combination of that three strings 
            if [ $name1 != $name2 -a $name2 != $name3 ]
            then
            echo $name1$name2$name3
            fi
        done
    done
done 

if you want also to print strings, like 123123123 and ABCABCABC, remove if condition

Upvotes: 1

Related Questions