Linux Automation Tip: Repeat Commands with Loops and Delays

in #making7 years ago (edited)

Linux and BASH

Unix and Linux are a lot more powerful for automation than people from other operating systems know, that power is under the hood in Macosx (via the BSD Unix foundations) and that power is making its way into Windows in a big way too. Let's take a look at one simple example ...

You might have seen my Python script for creating thumbnails.

What if I wanted to run it continuously?

Well, Linux has an app for that ;)

Create a new file and call it something like "do-thumbs.sh". Add the following to the file then save:

#!/bin/bash

while [ 1 ];
do
        python3 thumb.py
        sleep 60s
done

Now enter

chmod +x do-thumbs.sh

This will make your Shell Script executable.

Now if you run the script using

./do-thumbs.sh

It will repeat forever!

Sleep

Note we delay with the sleep command so that we are not pounding the machine.

Sleep can take several time delay options - specify the delay in seconds, minutes, hours or days.

s - seconds
m - minutes
h - hours
d - days

Repeat for a Fixed Count Using For Loops

What if you don't want it to loop forever?

Just replace the while line with

for x in {1..10}

Sort:  

You may also use watch command.

Eg. watch -n1 date +'%H:%M:%S:%N'

Beautiful. But maybe it's better to do it in Python?

import time
import sys

##
##code_def()
##

if __name__ == '__main__':

    delay, loops = sys.argv[1], sys.argv[2]

    for loop in range(loops):
        code_def()
        time.sleep(delay)
    

python app.py 10 2

I think it depends how much you will be using built-in linux commands versus coding, either way works :)

nice to know :)

You got a 2.14% upvote from @postpromoter courtesy of @makerhacks!

Want to promote your posts too? Check out the Steem Bot Tracker website for more info. If you would like to support the development of @postpromoter and the bot tracker please vote for @yabapmatt for witness!

what fun and interesting this publication. I did not know the options that linux can give us. thank you and keep informing us

Coin Marketplace

STEEM 0.16
TRX 0.12
JST 0.026
BTC 57387.61
ETH 2518.18
USDT 1.00
SBD 2.31