Loop / Repeat Terminal Commands 2

Terminal

Share
Loop / Repeat Terminal Commands

Hey

I want to extend your Terminal knowledge today by introducing a simple loop command. This is useful if you want to repeat or loop a Terminal command indefinitely. This is a simple bash script that has a variety of uses. The script is a simple one line command that needs very little adjusting on your part.

The first step is to open up Terminal. Then copy and paste, or type, the following into the Terminal prompt.

bash -c 'while [ 0 ]; do date;done'

This will activate a bash script, and will repeat the listed command indefinitely, press Control + C to stop the loop. Replace the word date, with any command you want to run. This loop works when the program you want to run will have a defined exit. For example the command date will display the current date and time and then return you to the command prompt. A command such as top, will display the command but will immediately open the command again the second you exit top.

The loop listed will run the command as fast as possible, this is a little bit of overkill and the majority of commands are best used when a small amount of delay is present after each command is run. To achieve this in the loop we are going to add a sleep command, to pause the loop for a certain number of seconds. To add this into the loop type the following:

bash -c 'while [ 0 ]; do date;sleep 1;done'

This will cause the loop to pause for one second before it is repeated.

A simple loop that I will begin to implement in a couple of commands. If you want to learn more about bash programming I recommend Bash Cookbook, among the many useful books found on Amazon. If you have any questions, comments or extensions to this code, please leave a comment using the form below.


If you want to keep up with the latests post from Mac Tricks And Tips I recommend you subscribe to the RSS Feed.

Where To Next?

  • Subscribe To Mac Tricks And Tips