How can I run a cron command with existing environmental variables?
In the crontab, before you command, add . $HOME/.profile
. For example:
0 5 * * * . $HOME/.profile; /path/to/command/to/run
Cron
knows nothing about your shell; it is started by the system, so it has a minimal environment. If you want anything, you need to have that brought in yourself.
Another option, which I find easier, is to run the script with cron and have the environment in the script.
In crontab -e file:
SHELL=/bin/bash
*/1 * * * * $HOME/cron_job.sh
In cron_job.sh file:
#!/bin/bash
source $HOME/.bash_profile
some_other_cmd
Any command after the source of .bash_profile will have your environment as if you logged in.
Another option, which I find easier, is to run the script with cron and tell bash to login (hence using /etc/profile.d/...
environment definitions)
In crontab -e
file:
*/1 * * * * bash -l -c './cron_job.sh'
*/1 * * * * bash -l -c 'php -f ./cron_job.php'
Any command after the source of .bash_profile
will have your environment as if you logged in.