Search code examples
bashbrace-expansion

Increase the amount of brace expansions given a number


I have a program that uses a brace expansion:

for X in {a..z}
    do echo $X;
done

I want to increase the amount of letters used in the brace expansion with a provided number. For example if the number 3 is provided:

for X in {a..z}{a..z}{a..z}
    do echo $X;
done

If the number 5 is provided:

for X in {a..z}{a..z}{a..z}{a..z}{a..z}
    do echo $X;
done

How can I do this in bash?


Solution

  • Here's one way. With a..z:

    $ a2z() { 
      k=""
      n=$1
      while [ $n -gt 0 ]
      do
        k="{a..z}$k"
        let n="$n-1"
      done
      echo $(eval "echo $k")
    }
    $ for X in $(a2z 3)
    do echo $X;
    done
    aaa
    aab
    aac
    ...
    

    Kinda useful, or at least interesting, using 0..1 as it shows each permutation for N bits.

    $ bitperms() {
      k=""
      n=$1
      while [ $n -gt 0 ] 
      do
        k="{0..1}$k"
        let n="$n-1"
      done
      echo $(eval "echo $k")
    }
    $ bitperms 4
    0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
    $ for X in $(bitperms 2);do echo "$X";done
    00
    01
    10
    11