Question

How can I set up my crontab environment in such a way so that it has access to built-in BASH variables such as $HOME, $PWD, $OLDPWD, $USER, $PATH, $PS1, etc., so that scripts that rely on these variables can run in crontab environment? Is this a matter of sourcing some files which I'm not aware of, or are matters slightly more complicated?

Was it helpful?

Solution

These variables are always set as expected: HOME, PWD, USER.

If you are scheduling your script like this:

0 0 * * * /path/to/script.sh

and the first line of the script is #!/bin/bash then probably it will source ~/.bashrc but not ~/.bash_profile or ~/.profile when running. Other than that, the variables you mention should work as expected. For example, if you change directories within your script, then OLDPWD and PWD will be updated. I don't see how PS1 would be relevant in a script.

On the other hand, if in your crontab you want to schedule a single command and you want .bashrc to be sourced, then you have to write like this:

0 0 * * * . .bashrc; somecmd
# or:
0 0 * * * bash -c somecmd

Also keep in mind that although you can set variables in a crontab, it works different from variables in a shell script. For example these work:

SHELL = /bin/bash
SHELL=/bin/bash
PATH=~/bin:/usr/bin/:/bin

This on the other hand won't do what you expect:

PATH=$HOME/bin:$PATH

As explained in man 5 crontab, values (anything after the =) are not parsed, so $HOME and $PATH in this example will be taken literally.

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top