Home > Enterprise >  Setting var env with bash script load by cron
Setting var env with bash script load by cron

Time:11-10

I would like to be able to play a script every hour from a crontab while recalling an environment variable previously defined at system startup (something like this: export EXTENRALIP=0 in a file like /etc/profile. This environment variable will be modified by this script and the value will be retrieved at the next rotation. I tried to do like this, but exporting the value does not change the variable

rotation.sh

#!/bin/bash

LOGFILE=/var/log/dns.log

. livebox.sh
. network.sh
. dns.sh


# Grab the var env
IPWAN=$(echo $EXTERNALIP)

# Grab the IPWAN
IP=$(get_livebox_ip)

# Set the var env if changed
if [ "$IPWAN" != "$IP" ]
    export EXTERNALIP=$IP

CodePudding user response:

It can't be done.

Regardless of the fact that cron jobs don't inherit any exisiting environment, the environment of your script is gone when it exits. This wouldn't work even without cron.

You can use shebang #!/bin/bash -l to have your script source /etc/profile, or use EXTERNALIP=0 /path/to/rotation.sh in crontab, but you could never update the variable anywhere except in the environment of each job.

You might be sourcing your scripts to make this work in your shell, but every cron job is a new shell, and its environment is gone when the job is finished.

CodePudding user response:

Like dan mentioned, I don't think that can be done.

Consider writing and reading the data from disk.

echo "$IP" > /somewhere/externalip
IPWAN="$(cat /somewhere/externalip)"
  • Related