0

I have this in my crontab:

* * * * * cd /etc && . ./cron.sh>>cron.log

In my cron.sh (which is executable) I have:

#!/bin/sh

echo "hello world"
export MyVar="abcd"

It runs both with cron and manually, however the environment variable is only set when I run it manually with the command:

. ./cron.sh

Can anyone please help. I know its something to do with source but I cant figure it out.

This does not work either:

* * * * * cd /etc && sh ./cron.sh>>cron.log
2
  • What are you trying to do? Commented Jun 3, 2019 at 14:50
  • I'm trying to set a variable for all users Commented Jun 3, 2019 at 14:50

2 Answers 2

5

. will export variables in the current shell, which is the one spawned by the cron, not yours.

If you want to add an extra variable to your shells, use the ~/.profile et al (specifically the /etc/profile that is shared by all users).

Sign up to request clarification or add additional context in comments.

2 Comments

Or /etc/profile, since that is already shared by all users.
@chepner that was part of my et al. ;) I'll update my answer to enlight that.
2

I'm trying to set a variable for all users

You cannot do that via a cron job.

In fact, in general, you can't do it at all. The environment variables of a shell cannot be set from outside the shell. The UNIX / Linux operating system architecture doesn't allow it.

You could could set an environment variable for all users via /etc/profile except ...

  1. the /etc/profile file is only executed when a user logs in, and
  2. the user can override any environment variables set there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.