Search code examples
nested-loopsash

Nesting for loop inside a while loop on one line


I am trying to run a script looping forever every ten seconds five times one second apart. How can I do this from command line instead of a script? This does not work:

while true; do; sleep 10 && for i in `seq 3` do; sleep 1 && date; done; done

This works in a script:

#!/bin/ash
while true; do
    sleep 10
    for i in `seq 3`; do
        sleep 1 && date
    done
done

If it's relevant this is to blink an led in a specific pattern on raspberry pi not to print the date the date command is just to see whats happening.


Solution

  • Try this:

    while true; do sleep 10 ; for i in `seq 3`; do sleep 1 && date ; done ; done
    

    No semi column should be used after do keyword. No need to use && before starting the for loop in your case. Using && before for loop mean, execute the loop only if sleep 10 command is success.

    In your case, though you use && before for loop or not, it gives the behavior would be same.