Search code examples
bashscriptingcron

How to simulate the environment cron executes a script with?


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?


Solution

  • Add this to your crontab (temporarily):

    * * * * * env > ~/cronenv
    

    After it runs, do this:

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

    This assumes that your cron runs /bin/sh, which is the default regardless of the user's default shell.

    Footnote: if env contains more advanced config, eg PS1=$(__git_ps1 " (%s)")$, it will error cryptically env: ": No such file or directory.