yak
yak

Reputation: 3930

How to run bash script from cron passing it greater argument every 15 minutes?

I have a simple script that I need to run every 15 minutes everyday (until I get to the last record in my database) giving it greater argument. I know how to do this with the constant argument - example:

*/15 * * * * ./my_awesome_script 1

But I need this, let's say, we start from 8:00 AM:

at 8:00 it should run ./my_awesome_script 1
at 8:15 it should run ./my_awesome_script 2
at 8:30 it should run ./my_awesome_script 3
at 8:45 it should run ./my_awesome_script 4
at 9:00 it should run ./my_awesome_script 5
...

How to make something like this?

I came up with temporary solution:

#!/bin/bash

start=$1
stop=$2

for i in `seq $start $stop`
do
        ./my_awesome_script $i
        sleep 900
done

Upvotes: 1

Views: 75

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753900

Writing a wrapper script is pretty much necessary (for sanity's sake). The script can record in a file the previous value of the number and increment it and record the new value ready for next time. Then you don't need the loop. How are you going to tell when you've reached the end of the data in the database? You need to know about how you want to handle that, too.

New cron entry:

*/15 * * * * ./wrap_my_awesome_script

And wrap_my_awesome_script might be:

crondir="$HOME/cron"
counter="$crondir/my_awesome_script.counter"
[ -d "$crondir" ] || mkdir -p "$crondir"
[ -s "$counter" ] || echo 0 > "$counter"
count=$(<"$counter")
((count++))
echo "$count" > $counter

"$HOME/bin/my_awesome_script" "$count"

I'm not sure why you use ./my_awesome_script; it likely means your script is in your $HOME directory. I'd keep it in $HOME/bin and use that name in the wrapper script — as shown.

Note the general insistence on putting material in some sub-directory of $HOME rather than directly in $HOME. Keeping your home directory uncluttered is generally a good idea. You can place the files and programs where you like, of course, but I recommend being as organized as possible. If you aren't organized then, in a few years time, you'll wish you had been.

Upvotes: 1

Related Questions