Monday, January 13, 2020

Bash Script Runs From Terminal But Fails When Run From Anacrontab

The quick answer: Do not use an environmental variable in a bash script run from either cron or anacrontab.

I was developing a bash script to use tar to backup my files. In researching this, I ran across using the Linux environmental variable $SECONDS. Seemed pretty nifty as I could then get the elapsed time for the operation of the backup program.  My program worked well, as expected, when executed from the terminal, but failed when executed by anacrontab. In researching how to solve this problem, I ran across an old post that stated "If you run a script from cron make sure the script doesn't use any environment variables. Those variables are present when you are logged in as user X, but are not present when running from cron." This immediately  answered the question.

I was surprised though, at the number of posts asking for advise on how to resolve this type of problem but who did not not receive the answer above.

 I solved this issue by using the date command to set the start and end times. Then subtracting the values to get the elapsed time for the backup operation.
Also, I am sure that there are ways to use an environmental variable in either cron or anacrontab, but I did not want to delve into the issue further.