views:

382

answers:

7

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?

A: 

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.

jn80842
This is why I'm asking simulate
Jorge Vargas
+2  A: 

Cron provides only this environment by default :

  • HOME user's home directory
  • LOGNAME user's login
  • PATH=/usr/bin:/usr/sbin:.
  • SHELL=/usr/bin/sh

If you need more you can source a script where you define your environment before the scheduling table in the crontab.

gregseth
+1: this is exactly what I get.
jldupont
+3  A: 

You can run:

env - your_command arguments

This will run your_command with empty environment.

dimba
cron doesn't run in a completely empty environment, does it?
jldupont
+1  A: 

By default, cron executes its jobs using whatever your system's idea of sh is. This could be the actual Bourne shell or dash, ash, ksh or bash (or another one) symlinked to sh (and as a result running in POSIX mode).

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 $PATH yourself.

Dennis Williamson
This is exactly what I'm trying to solve. We get tons of problems with scripts that assume something by mistake. Doing full paths and setting env variables and all the junk ends up with horrible huge unmaintainable cron lines
Jorge Vargas
re *sh sorry I grew up with bash = shell so it's hard to me to remember the alternatives (and sometimes better) shells.
Jorge Vargas
Dennis Williamson
+5  A: 

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.

Jens Carlberg
Sorry this confused me. isn't "env - script" enough?
Jorge Vargas
That will give you an empty environment. When you run scripts through cron, the environment isn't empty.
Jens Carlberg
+2  A: 

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:

http://libslack.org/daemon/

Randy Proctor
+4  A: 

Add this to your cron:

30 08 * * * env > ~/cronenv

After it runs, do this:

env - `cat ~/cronenv` /bin/sh

This assumes that your cron runs sh. I believe this is the default.

mmccoo