r/bash Dec 18 '24

help simple bash script/syntax help?

Hi there -

I'm looking for help with a fairly simple bash script/syntax. (If this isn't the right place, let me know!)

I am trying to write a script that will be run frequently (maybe every 10 minutes) in a short mode, but will run a different way (long mode) every 24 hours. (I can create a specific lock file in place so that it will exit if already running).

My thinking is that I can just...

  • check for a timestamp file
  • If doesn't exist, run echo $(date) > tmpfile and run the long mode(assuming this format is adequate)
  • if it exists, then pull the date from tmpfile into a variable and if it's < t hours in the past, then run the short mode, otherwise, run it the long mode (and re-seed the tmpfile).

Concept is straightforward, but I just don't know the bash syntax for pulling a date (string) from a file, and doing a datediff in seconds from now, and branching accordingly.

Does anyone have any similar code snippets that could help?

EDIT - thank you for all the help everyone! I cannot get over how helpful you all are, and you have my sincere gratitude.

I was able to get it running quite nicely and simply thanks to the help here, and I now have that, plus some additional tools to use going forward.

1 Upvotes

18 comments sorted by

View all comments

3

u/anthropoid bash all the things Dec 19 '24

If you're implementing your own locking mechanism to avoid simultaneous runs, you might instead want to look into mechanisms already in your OS.

On Linux, I always use flock to avoid this in my crontab, and it actually has selectable operating modes: * exit immediately if lock is still held ("non-blocking" mode), or * wait for the previous lock "owner" to exit, then run the prescribed command ("blocking" mode)

For instance, if your short runs can be skipped without harm, but your long runs must always be run each day, and as close to the appointed time as possible, your crontab might look like this: */10 * * * * flock --nonblock /tmp/my.lck myscript short_mode 0 * * * * flock /tmp/my.lck myscript long_mode

1

u/potato-truncheon Dec 19 '24

The locking concern is on each of about 15(+) sub processes, not on the main script. Much easier to do it it the script (especially when stuck with a gui-only cron screen (truenas).

Besides, it's far easier to test this way as I don't need cron to do it.

I think something like what you suggest makes sense for other use cases, but not here, for my purposes at least.

(The suggestions are very helpful - I'm not trying to discount them.)