Run any script manually as Cron
This is a common problem I’ve always had, where my own script running under cron would often fail, but when ran directly as my user they would behave normally.
Having to wait for cron to schedule your test script to run is annoying and a huge time waste, so instead you can choose to run the script yourself manually as cron and see what’s wrong.
This is based on the answers from this page.
Step 1: Create a cron entry to extract your cron environment
crontab -e
- Add
* * * * * /usr/bin/env > /home/<username>/cron-env
where <username> is your username. - Save the crontab
This will run all the time and save the cron environment to the given cron-env file in your home directory.
You can remove the entry afterwards or set it to run less often (I have it run every 30 minutes) if you want.
Step 2: Create a wrapper script
Create the following file
#!/bin/sh
. "$1"
exec /usr/bin/env -i "$SHELL" -c ". $1; $2"
and call it run-as-cron
, make it executable with chmod +x <filename>
and put it somewhere in your $PATH
(I have a $HOME/bin
directory with all my custom scripts).
Step 3: Run the script
$ run-as-cron ~/cron-env 'myscript.sh'
This will execute ‘myscript.sh’ as if it were being called directly from cron, so you can inspect any possible failures or issues without having to wait for cron to actually run it for you.