Saqib Rao
Saqib Rao

Reputation: 47

Writing infinite bash loop

How to write an infinite loop echoing numbers from 1 to infinite in bash. I am using a for loop but it is being killed by bash on using value more than 100000000.

#!/bin/bash
for a in {1..100000000..1}
do
  echo "$a"
done

any alternative for it?

Upvotes: 2

Views: 347

Answers (3)

cwallenpoole
cwallenpoole

Reputation: 82028

Can't you just do a while true;?

a=0
while true;
do
    a=$((a+1))
    # $[$a+1] also works.
    echo "$a"
done

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60068

This should work in all POSIX shells:

i=0; while :; do echo "$((i+=1))"; done

: is interchangeable with the true builtin (which you can use instead): it's a no-op that always succeeds (=returns 0).

If integer overflow bothers you, and you want arbitrary precision with standard tools:

nocontinuation(){ sed ':x; /\\$/ { N; s/\\\n//; tx }'; }
i=99999999999999999999999999999999999999999999999999999999999999999999;
while : ; do i=`echo "$i + 1" | bc | nocontinuation`; echo "$i"; done

This would be quite slow, because it spawns in each iteration. To avoid that, you could reuse one bc instance and communicate with it over pipes:

#!/usr/bin/bash
set -e
nocontinuation(){ sed -u ':x; /\\$/ { N; s/\\\n//; tx }'; }
trap 'rm -rf "$tmpdir"' exit
tmpdir=`mktemp -d`
cd "$tmpdir"
mkfifo p n 
<p bc | nocontinuation >n &
exec 3>p
exec 4<n

i=99999999999999999999999999999999999999999999999999999999999999999999;
while : ; do 
  echo "$i + 1" >&3
  read i <&4
  echo "$i"
done

Upvotes: 4

CristianHG
CristianHG

Reputation: 452

Have you tried doing a while loop?

#!/bin/bash

num=0;

while :
do
    num=$((num+1))
    echo "$num"
done

Upvotes: 5

Related Questions