OneBite.Dev - Coding blog in a bite size

run code program on terminal every x time (seconds)

In order to run any command or program every X seconds or any time from your Mac terminal, you can utilize a shell loop with the sleep command.

In order to run any command or program every X seconds or any time from your Mac terminal, you can utilize a shell loop with the sleep command.

Sample running nodeJS script

The following command runs a given script (`script.js` for instance) every 30 seconds:

while true; do node script.js; sleep 30; done

In the command above:

- `while true; do … done` is a loop that runs forever.

- `node script.js` runs your Node.js script.

- `sleep 30` pauses the loop for 30 seconds before starting the next iteration.

Make sure to replace `script.js` with the path to the actual script you want to run. Also remember to press `CTRL+C` to stop the loop.

Warning running infinite loop

As a side note, you should be careful about running scripts in infinite loops and consider adding some error handling to ensure that it doesn’t crash your system in case something goes wrong.

mac terminal bash