How to run a command as if it is called from cron

cron

I write a script and set it as a cron job.
But due to a difference of environment variables it doesn't work as it should be.

In that case I change a little bit with crontab -e and set a cron job time closest minute, and wait next minute to come to show the result. I feel this is a totally absurd approach, but I don't know better way to do it.

If there is a way to run a script as if it is called inside cron job, I'm going to use it.

Does anyone know how to do it?

Best Answer

Here is how to do the other way around: forcing cron execution to use your login environment:

bash -lc "your_command"

From the bash manual:

-c string     If the -c option is present, then commands are read from string.
              If there are arguments after the string, they are assigned to the
               positional parameters, starting with $0.
-l            Make bash act as if it had been invoked as a login shell
               (see INVOCATION below).

INVOCATION (a bit stripped):

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

To known more:

Related Question