What to do when a shell command doesn't work in crontab
So you have a nice command which should run every 5 minutes.
You correctly configure your crontab with the help of the super-simple , crontab.guru.
You are sure about it, you test it, it works.
Ok so I'm gonna leave it running for the night, every 5 minutes and tomorrow morning results will be there.
You wake up and....
It did not run!
But it works if I run it on the terminal! - What the heck?
The workaround
1 - Put it in a script
A very good workaround is to place whatever command you want to run in a dedicated script.
*/5 * * * * /home/user/archiver.sh
Content of script:
cp /home/user/results.csv /home/user/results_archive/$(date +%Y%m%d%H%M)_results.csv
Remember to give it executable permissions:
chmod +x /home/user/archiver.sh
Otherwise crontab (and you and anybody else) is not gonna be
able to execute it!*
2 - What if it still does not work?
In this case it should work by exporting your PATH inside the script.
First get the contents of the PATH variable for your user by running the command
env
In the command's output you will have a line called
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:....
....
Copy the whole line and place it in your script at the top.
Content of script:
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:....
cp /home/user/results.csv /home/user/results_archive/$(date +%Y%m%d%H%M)_results.csv
Nice site recommendation.
THX
You're welcome. Once you see it, you'll forget about how crontab scheduling works :) it's like the portable calculator for crontab users.