A friend of mine known for inhumane treatment of machines wanted to stress their CPU, and so wrote a one-liner like this:

for z in {1..100000000};do num1=$(($z * $z)) && echo $num1;done

When executed, this loop just sits with no output, and a quick look at top shows bash consuming massive amounts of memory (gigabytes after a few minutes).

As written, I'd expect this process to run sequentially - as in, pass in the z variable, calculate it, echo the result, repeat.

Instead, trying this with smaller upper bounds makes it look as if everything is calculated up front, and then dumped to the screen en masse. As in, it sits for a moment doing the calculations, then does the echo's all at once.

Why does this loop behave this way?


As described here, the range operator builds the range (creates an array of integers) before letting you do things to it such as iterating over it. You may be better off with a while loop:

 z=1 ; while [[ $z -le 100000000 ]] ; do num1=$(($z * $z)) && echo $num1 ; z=$(($z + 1)) ; done

(Although this is unlikely to really stress a CPU as the echo causes some relief. My own system only reaches about 30% utilization while running this.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.