# Where can I set environment variables that crontab will use?

LinuxOperating SystemOpen Source

In normal cases we make use of the bash_profile or bashrc in case of Ubuntu and zshrc in case of Mac OS, to set our environment variables and then those variables are made available to us everywhere on the terminal we want.

Let’s consider a simple example where we have some environment variable in bash_profile and we are making use of it in the terminal.

Consider the bash_profile output shown below −

immukul@192 dir1 % cat ~/.bash_profile
export JAVA_HOME=$(/usr/libexec/java_home) export PATH=$PATH:/usr/local/node/bin
export GOROOT=/usr/local/go
export GOPATH=/Users/immukul/go_projects

As we can see there are many variables present in the bash_profile file, we can use these variables in any terminal by just calling out their name.

Consider the example shown below −

echo $GOROOT ## Output /usr/local/go Now what we want is to be able to access these variables that we have inside the bash_profile or bashrc to be available inside the crontab. Let’s first explore and understand what a crontab is. A crontab is nothing but a list of commands that we can run during a cron job. A cron job is a utility that schedules automatic execution of commands at specific times. We can start a cron job with the help of bash script by following the commands shown below − crontab -e  This will open a file which you can edit, insert the cron job shell script in the above file and then close that file. Just insert the code shown below in the above file. * * * * * sample.sh The above command contains 5 *, where each * indicates the time and then follows the stars. We have the script which we want to run as a cron job. In the sample.sh we need to write the following command to make the environment variables available to it. Consider the example shown below (sample.sh) ## Example #!/bin/bash -l echo$PATH
for f in *.txt; do mv "$f" "${f// /_}"; done

The command #!/bin/bash -l will allow your cron shell script to pick any environment variable you want.

## Output

sh-3.2# ./sample.sh
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Library/Apple/usr/bin
Published on 31-Jul-2021 12:27:56