Until not so long ago, to add my own cron jobs I always had the habit of modifying
/etc/crontab on my FreeBSD system which turned out to be wrong. In simple words, there are two types of crontab files:
- System crontab which should not be altered due to the troubles it cause during FreeBSD upgrades
- User crontab which has one less column than the system crontab file
So, I found out that the proper way it should be done is using crontab uitlity as it follows:
To create a crontab for current user:
$ crontab -e
To create a crontab for a specific user (e.g.
$ crontab -e -u babaei
This should create the user crontab files inside
/var/cron/tabs/babaei) and open up your system’s default text editor which in my case is nano. It is better to avoid modifying these files directly and always modify them through
crontab -e since you don’t have to restart the
cron service manually this way. By the way,
-e stands for editor mode.
This is a typical
root user crontab file I use on one of my production servers (as you can see there is no who column since it’s useless in user’s own crontab file format):
To list the cron jobs in the crontab for the current user at any time, use the following command:
$ crontab -l
Or for a specefic user you can try this one (e.g.
$ crontab -l -u babaei
As you can see I added a few environment variables to the beginning of my crontab file. This is due to the fact that your cron scripts may not run properly due to executable path issues (e.g. you forgot to use absolute paths for commands you called in your scripts, so it won’t be able to find those commands you used in your scripts). If you want to test whether your scripts run properly or not, you should replicate the environment that would be used to run your scripts by testing them with a limited set of environment variables set by cron:
$ env -i \ SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin \ HOME=/root LOGNAME=Charlie \ /path/to/your/scriptname.sh
To see what these variables such as
SHELL do, please refer to crontab’s manpage or documentation.
I almost forgot to mention that, there is another common pitfall when you are going to run your script or binary executables through a crontab. And that is, they should have executable permission which can be achieved by one of the following commands:
Make it executable for the owner of the file:
$ chmod u+x /path/to/your/executable
Make it executable for everyone:
chmod a+x /path/to/your/executable
- How to disable HP Proliant ML350p Gen8 P420i RAID controller, enable HBA mode (a.k.a. pass-through), and perform a FreeBSD root on ZFS installation
- A quick workaround for Unreal Engine Modeling Tools Editor Mode plugin not showing up on Linux and macOS
- Host Unreal Engine 4 projects on Microsoft Azure DevOPS with unlimited cost-free Git LFS quota
- Gregorian / Jalali (a.k.a. Persian Calendar) Date Conversion in C++ using boost::locale