3

I was working on a simple daemon example and noticed that the following command prints same value of time on every iteration.

/bin/bash -c "while true; do echo `date`; sleep 1; done"

Output:

Wed Dec 25 08:00:47 UTC 2013
Wed Dec 25 08:00:47 UTC 2013
Wed Dec 25 08:00:47 UTC 2013

However, If I put the above code in a script and then run the script, it gives the expected output.

#!/bin/bash
while true; do
   echo `date`
   sleep 1
done

Output:

Wed Dec 25 08:02:58 UTC 2013
Wed Dec 25 08:02:59 UTC 2013
Wed Dec 25 08:03:00 UTC 2013

How is this possible? Is this the expected output?

goyalankit
  • 843
  • 8
  • 23

1 Answers1

8

It behaves exactly as expected. The date substitution is performed by caller bash, not by callee. Alter the command this way:

/bin/bash -c 'while true; do echo `date`; sleep 1; done'

and you get the behavior expected by you.

The difference is in single and double quoted strings - the latter ones are subject to the parameters expansion and command substitution

Serge
  • 6,088
  • 17
  • 27
  • 1
    Nit: What OP is seeing is not parameter expansion, but rather *[command substitution](http://mywiki.wooledge.org/CommandSubstitution)*. [More on quotes.](http://mywiki.wooledge.org/Quotes) – l0b0 Dec 25 '13 at 10:28