Search code examples
arrayslinuxbashbrace-expansion

Understanding code ({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})


I saw the following code in Bash shell Decimal to Binary conversion and I was wondering how it works? I tried googling with no avail.

D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})

echo ${D2B[7]}

What does the code above do?


Solution

  • {N..M}, for integer literals N and M, generates the series of integers from N to M, inclusively, separated by spaces. This is called a "brace expansion", and is a bashism. As you can see, all brace expansions are done before adding spaces between them.

    variable=({some expansion}) puts each of the expanded items in an array, and ${variable[index number]} extracts the value at that index. So your code effectively returns the number seven in binary string form.