cron ignores variables defined in ".bashrc" and ".bash_profile"
You can source the file you want at the top of the script or beginning of the job for the user that is executing the job. The "source" command is a built-in. You'd do the same thing if you made edits to those files to load the changes.
* * * * * source /home/user/.bash_profile; <command>
or
#!/bin/bash
source /home/user/.bash_profile
<commands>
Because it's not an interactive shell. The same happens when you open some terminals.
Have a look at this question: What is the .bashrc file? | Super User
And also at this one:
What's the difference between .bashrc, .bash_profile, and .environment? | Stack Overflow
Different scripts fire depending on if the connection is a login shell (or not), an interactive shell (or not), or both.
If you want to make bashrc you'll need to make this change:
When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of the PATH variable is not used to search for the file name.
As noted above, if a non-interactive shell is invoked with the
--login
option, Bash attempts to read and execute commands from the login shell startup files.
Source: Bash Startup Files | Bash Reference Manual | gnu.org
You may not be able to run source
if the sh
shell is being used. This can be changed by adding the following line in your crontab:
SHELL=/bin/bash
* * * * * source "/root/.bashrc"; <command>
You can also specify the environment:
BASH_ENV="/root/.bashrc"
* * * * * <command>
or you can use your local /home/user/.bashrc
if it is a user cron job (e.g. crontab -e
).
Note that .bash_profile
can replace .bashrc
, if it exists.
Credit: How to change cron shell (sh to bash)?