Ubuntu – Set environment variable UBUNTU 18.04 (bionic) – Crontab

bashcronenvironment-variablessql

Firstly, sorry for my English.

My situation is:

  • Have a Ubuntu 18.04
  • Want to execute with crontab python & sh scripts
  • Result: /usr/lib/oracle/12.2/client64/bin/sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

The variables i want to add are defined like this:

export ORACLE_HOME=/usr/lib/oracle/12.2/client64
export PATH=$PATH:$ORACLE_HOME/bin
export OCI_LIB_DIR=$ORACLE_HOME/lib
export OCI_INC_DIR=/usr/include/oracle/12.2/client64
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME

I configure the environment variable in many ways to avoid this error:

  • ~/.bashrc
  • ~/.profile
  • /etc/environment
  • Creating myvars.sh file in /etc/profile.d

The problem is when i configure the variables for my user (in ~/.profile, for example)and I execute on the terminal one python or sh script that use SQL connection, ends well and doesn't give any error. But when the python is execute through crontab, appears in the log the error:

/usr/lib/oracle/12.2/client64/bin/sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

i read in other forum threads that ~./bash_profile is used for define environment variables but don't have this file.
thanks

Best Answer

cron runs jobs in its own minimal environment and doesn't itself read any of the shell startup files such as those in /etc/profile.d/ - by default it's just something like

LANGUAGE=en_CA:en
HOME=/home/steeldriver
LOGNAME=steeldriver
PATH=/usr/bin:/bin
LANG=en_CA.UTF-8
SHELL=/bin/sh
PWD=/home/steeldriver

You have a couple of options:

  1. set the variables in a script, and run that from cron. In the case of shell scripts, that's easy (just export them at the top of the script - or source an environment file if you prefer). For Python scripts you may find it easiest to wrap the python call inside a shell script where you can set up the environment first.

  2. define the environment as a sequence of name = value pairs inside the crontab like

    ORACLE_HOME = /usr/lib/oracle/12.2/client64
    * 5 * * * /path/to/some/executable
    

    (spaces are allowed around the = since it's not a script); however note that this method does not expand variables so you can't do stuff like PATH=$PATH:/whatever

See man 5 crontab for details.