Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 400
Jeroen Vermeltfoort Avatar asked Jun 24 '17 16:06

Jeroen Vermeltfoort


People also ask

What does ${} mean in bash?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.

What are {} used for in bash?

Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..".

How do you escape brackets in bash?

Bash Character Escaping. Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.


1 Answers

{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.

like image 59
l0b0 Avatar answered Oct 12 '22 16:10

l0b0