# array creation from equation output

I want to for example divide all integers from 1 to 5 by 8 and put them in an array. I was thinking something similar to the code below but I'm sure it's wrong and dirty:

`````` COUNTER=0
until [  \$COUNTER -lt 8 ]; do
\${steps[\$COUNTER]}=1+(5-1)/8*\$COUNTER
let COUNTER+=1
done
``````

Is there anyway to do this cleanly if my code is correct at all?

## 3 Answers

`bash` can only do integer arithmetic. Use `bc` for floats:

``````from=1
to=5
steps=8
for c in \$(seq 0 \$steps) ; do
ar[c]=\$(echo \$(bc -l <<< "\$from + (\$to - \$from) / \$steps * \$c"))
done
echo "\${ar[@]}"
``````
• The OP wants to divide all integers from 1 to 5 by 8 and store that in the array. – terdon Oct 7 '15 at 13:29
• @terdon: I understood the question differently before you edited it. – choroba Oct 7 '15 at 13:54
• I know, it really wasn't clear, hence the comment and lack of downvote :) – terdon Oct 7 '15 at 13:56
• I get really massive values with a lot of zeros in front of them any fixes? – Raymond Ghaffarian Shirazi Oct 7 '15 at 16:21
• @RaymondGhaffarianShirazi: You can shorten the output of `bc` by declaring `scale`: `bc -l <<< "scale=3; \$from + ...` – choroba Oct 7 '15 at 19:15

The `seq` command can increment by a float:

``````declare -a steps=(\$(seq 1 .5 5))
``````

You can get the increment with `echo 'scale=1;(5-1)/8'|bc`

Yes, but since bash doesn't do floating point arithmetic, you'll need to use another tool and save its output in the bash array. For example:

``````\$ perl -le 'print \$_/8 for 1..5'
0.125
0.25
0.375
0.5
0.625
``````

Save in an array with:

``````array=( \$(perl -le 'print \$_/8 for 1..5') )
``````