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?
${} 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.
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 "..".
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>.
{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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With