1

Found this snippet of code which uses an array in Bash.

unset var1[@]

for i in {0..23}
do
    var1[10#$i]="some data"
done

When setting the element with data, what's that 10# in front of the element number for?

I know that for showing the total number of elements you can use echo ${#var1[@]} but I don't think the hash in setting the element has something to do with total size.

1 Answer 1

6

In arithmetic expressions, you can use # to specify base:

$ echo $((2#1110))
14

Using 10#$i would prevent i=08 from failing with value too great for base and interpret it as 8. For 0 .. 23, it's equivalent to just i.

Sign up to request clarification or add additional context in comments.

4 Comments

That is bizarre.. I never would have guessed it. Yup, without 10# the i=07 goes fine and i=08 fails with "-bash: 08: value too great for base (error token is "08")". Whoa... So pardon my ignorance, what is the default base for defining the array element number then?
Decimal, but the shell would automatically interpret it as octal if the number starts by '0'. Is the same that the leading '0x' for hexadecimal numbers.
I'm gonna chmod myself outta here.. Thanks all... :-)
You can use it for bases from 2 to 64. Nice: echo $((50#A0)) will print 1800 (50*36) and echo $((64#_0)) 4032.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.