I normally have several problems with how cron executes scripts as they normally don't have my environment setup. Is there a way to invoke bash(?) in the same way cron does so I could test scripts before installing them?
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
Add this to your cron:
After it runs, do this:
This assumes that your cron runs /bin/sh, which is the default regardless of the user's default shell. |
|||||||||||||||||||||
|
|
Cron provides only this environment by default :
If you need more you can source a script where you define your environment before the scheduling table in the crontab. |
|||||||||
|
|
Couple of approaches:
|
|||||
|
|
You can run:
This will run your_command with empty environment. |
|||||||||||||
|
|
Depending on the shell of the account
or
From http://matthew.mceachen.us/blog/howto-simulate-the-cron-environment-1018.html |
|||
|
|
|
Create a cron job that runs env and redirects stdout to a file. Use the file alongside "env -" to create the same environment as a cron job. |
|||||||||
|
|
Answering six years later: the environment mismatch problem is one of the problems solved by The most common issue to cause cron jobs to fail when they pass manually is the restrictive default
By contrast, the default
So there's already a better chance that a systemd timer is going to find a binary without further hassle. The downside with systemd timers, is there's a slightly more time to set them up. You first create a "service" file to define what you want to run and a "timer" file to define the schedule to run it on and finally "enable" the timer to activate it. |
||||
|
|
|
Don't forget that since cron's parent is init, it runs programs without a controlling terminal. You can simulate that with a tool like this: |
|||
|
|
|
By default, The best thing to do is make sure your scripts have what they need and to assume nothing is provided for them. Therefore, you should use full directory specifications and set environment variables such as |
|||||||||||||
|
|
Another simple way I've found (but may be error prone, I'm still testing) is to source your user's profile files before your command. Editing a /etc/cron.d/ script:
Would turn into:
Dirty, but it got the job done for me. Is there a way to simulate a login? Just a command you could run? EDIT: This seems to be a solid solution: http://www.epicserve.com/blog/2012/feb/7/my-notes-cron-directory-etccrond-ubuntu-1110/
|
||||
|
|
|
Answer https://stackoverflow.com/a/2546509/5593430 shows how to obtain the cron environment and use it for your script. But be aware that the environment can differ depending on the crontab file you use. I created three different cron entries to save the environment via 1. Global /etc/crontab with root user
2. User crontab of root (
|
|
I don't believe that there is; the only way I know to test a cron job is to set it up to run a minute or two in the future and then wait. |
|||||
|