Bash Seq – Seq and Brace Expansion Failing

.seqbashbrace-expansion

IINM my system is failing when bashing

for i in {0..10000000}; #   Seven zeroes.
do
    false;
done #   `bash` exited and its `tmux` pane/window was closed.

or

for i in $(seq 0 10000000); #   Seven zeroes.
do
    false;
done #   `bash` exited and its `tmux` pane/window was closed.

but not when

for i in {0..1000000}; #   Six zeroes.
do
    false;
done #   Finished correctly.

Can you please briefly explain the internals of this behavior and prompt a workaround for getting the task done?

Best Answer

for i in {0..1000000} and for i in $(seq 1000000) both build up a big list and then loop over it. That's inefficient and uses a lot of memory.

Use:

for ((i = 0; i<= 1000000; i++))

instead. Or POSIXly:

i=0; while [ "$i" -le 1000000 ]; do
  ...
  i=$(($i + 1))
done

Or:

seq 1000000 | xargs...

To get a file full of CRLFs:

yes $'\r' | head -n 1000000 >  file

Generally, loops should be avoided when possible in shells.

Related Question