0

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?

Digvijay S
  • 2,665
  • 1
  • 9
  • 21
Alon Arad
  • 101
  • 7
  • 1
    Does this answer your question? [Difference between single and double quotes in Bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) All the `$(` are expanded before entering `sh`. – KamilCuk Mar 16 '20 at 10:58
  • @KamilCuk can you elaborate? – Alon Arad Mar 16 '20 at 11:06
  • 1
    Great question, I had this problem once and moved to a python script after giving up – Steinfeld Mar 16 '20 at 11:17
  • You don't need `$(( ... ))` around the variables used with `-ge`; `[ "$CONTAINERS_COUNT" -ge "$i" ]` is fine. – chepner Mar 16 '20 at 17:02

2 Answers2

2

Expansions inside " work.

With set -x it looks like this:

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

You loop is expanded to while [ 0 -ge 0 ] before executing sh. So all sh sees is [ 0 -ge 0 ] - an endless loop.

I suggest using single quotes for script content to handle most quoting problems and pass environment using exported variable or by script positional arguments:

nohup sh -c '
   CONTAINERS_COUNT=$1
   i=1;
   while (( CONTAINERS_COUNT >= i )); do
      i=$((i+1))
      date
   done
' -- "$CONTAINERS_COUNT" &

Side note: it's just seq "$CONTAINERS_COUNT" | xargs -I{} date

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

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
:=>
Digvijay S
  • 2,665
  • 1
  • 9
  • 21