Jimmy
Jimmy

Reputation: 12517

Bash cannot set environment variable

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

Upvotes: 0

Views: 1696

Answers (2)

Matthieu
Matthieu

Reputation: 3117

. 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).

Upvotes: 5

Stephen C
Stephen C

Reputation: 719386

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.

Upvotes: 2

Related Questions