Friday, October 29, 2021

[SOLVED] Incrementing while loop inside nohup causes an infinite loop

Issue

while this works in sh

i=1; while [ $(( $CONTAINERS_COUNT )) -ge $(( i )) ]
do
    i=$((i+1))
    date
done

with 5 dates output (export $CONTAINERS_COUNT=5)

the following enters to an infinity loop

nohup sh -c " i=1; while [ $(( $CONTAINERS_COUNT )) -ge $(( i )) ]
do
    i=$((i+1))
    date
done &"

what am I doing wrong?


Solution

you need to put script in ' quotes.

:=>sh -c 'i=1; while [ $(( $CONTAINERS_COUNT )) -ge $(( i )) ]
do
    i=$((i+1))
    date
done &'
:=>Mon Mar 16 11:14:01 GMT 2020
Mon Mar 16 11:14:01 GMT 2020
Mon Mar 16 11:14:01 GMT 2020
Mon Mar 16 11:14:01 GMT 2020
Mon Mar 16 11:14:01 GMT 2020

Explanation: Single quote will treat string at it is. While double quote will expand.

:=>i=4
:=>sh -c "i=5; echo $i"
4
:=>sh -c 'i=5; echo $i'
5
:=>


Answered By - Digvijay S