Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I set environment variables that crontab will use?

I have a crontab running every hour. The user running it has environment variabless in the .bash_profile that work when the user runs the job from the terminal, however, obviously these don't get picked up by crontab when it runs.

I've tried setting them in .profile and .bashrc but they still don't seem to get picked up. Does anyone know where I can put environment vars that crontab can pick up?

like image 610
James Avatar asked Feb 09 '10 14:02

James


People also ask

Where do we set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

What path does crontab use?

When you create a crontab file, it is automatically placed in the /var/spool/cron/crontabs directory and is given your user name. You can create or edit a crontab file for another user, or root, if you have superuser privileges.

Where are Cronjobs located Linux?

The cron jobs are listed in crontab files and are located in the cron spool area /var/spool/cron/crontabs. Cron searches for these files and load them in the memory for execution.


2 Answers

You can define environment variables in the crontab itself when running crontab -e from the command line.

LANG=nb_NO.UTF-8 LC_ALL=nb_NO.UTF-8 # m h  dom mon dow   command  * * * * * sleep 5s && echo "yo" 

This feature is only available to certain implementations of cron. Ubuntu and Debian currently use vixie-cron which allows these to be declared in the crontab file (also GNU mcron).

Archlinux and RedHat use cronie which does not allow environment variables to be declared and will throw syntax errors in the cron.log. Workaround can be done per-entry:

# m h  dom mon dow   command * * * * * export LC_ALL=nb_NO.UTF-8; sleep 5s && echo "yo" 
like image 188
carestad Avatar answered Sep 21 '22 13:09

carestad


I got one more solution for this problem:

0 5 * * * . $HOME/.profile; /path/to/command/to/run 

In this case it will pick all the environment variable defined in your $HOME/.profile file.

Of course $HOME is also not set, you have to replace it with the full path of your $HOME.

like image 30
Vishal Avatar answered Sep 22 '22 13:09

Vishal