Question

I am trying to setup cron in a Unix environment to sync my code and config files to a backup folder every hour.

I need this to happen whenever I'm logged into my work terminal and at an hourly frequency. So, I inserted the following into my .bashrc file:

0 * * * * rsync -avz ~/codes/ /cheap/code_bkp

However, now when I'm logged into multiple work terminals, each of them run the job independently and I get multiple emails(1 for each terminal) every hour.

I would like to ensure only 1 terminal runs the cron job. Kindly suggest some way of doing so and avoiding the multiple terminal issue.

Was it helpful?

Solution

I think what you want is something along the lines of a reference count: if you put this in .bashrc

( counter=$(cat ~/.login_count); echo $(( $counter + 1 )) > ~/.login_count )

and something like this in .bash_logout

( counter=$(cat ~/.login_count); echo $(( $counter - 1 )) > ~/.login_count )

Then ~/.login_count will contain the number of active terminal sessions, assuming you always log out cleanly.

You can then test that this is non-zero in your cronjob to see if at least one terminal is logged in:

0 * * * * [ $(cat ~/tmp/counter) > 0 ] && do_backup

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top