I have problem in accessing a shell variable while running cron job. Actually i created a job which prints two shell variable values into a env.output file.

I am writing cron job using command $ crontab -e (without sudo user).

My crontab configuration file looks like this:-

# varibales

# Jobs
* * * * * echo "$HOME and $JOBS_PATH" >> ${HOME}/env.output 2>&1

So, now when i see the contents of file env.output , i get this output

/home/ubuntu and ${HOME}/cronjobs

which is not expected i assumed.

I want my output should looks like this:-

/home/ubuntu and /home/ubuntu/cronjobs

Suggest me some way to handle this issue.


I have problem in accessing a shell variable

HOME as defined at the top of a crontab is not a shell variable, is an environment variable.

You can't reference environment variables at the top of a crontab, as no shell processes them and thus they're not expanded (and interpreted literally).

You'll have to set JOBS_PATH manually:

# ...
# ...

This is a limitation of the cron daemon. See this from the manpage of crontab:

The value string is not parsed for environmental substitutions or replacement of variables, thus lines like:

     PATH = $HOME/bin:$PATH

will not work as you might expect.

You can do a workaround, since bash treats the tilde (~) as substitution of $HOME. Therefore use:

  • Upvoted this since apparently it works, but I'm still a bit puzzled at why it works. AFAIU environment variables set at the top of a crontab are processed by cron, not by the shell. Could you expand on this a bit? Mainly I don't understand why a variable wouldn't be expanded but a tilde would, seems pretty much an arbitrary behavior (i.e. it looks like that is handled that way by cron on purpose). – kos Nov 18 '15 at 10:22
  • sorry @kos i was in hurry , so i wrongly upvoted this answer. Your solution works really. Now i write full path to environment variable. – Akshay Pratap Singh Nov 19 '15 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.