XJDHDR XJDHDR - 1 year ago 139
Linux Question

Import PATH environment variable into Bash script launched with cron

When creating Bash scripts, I have always had a line right at the start defining the

environment variable. I recently discovered that this doesn't make the script very portable as the
variable is different for different versions of Linux (in my case, I moved the script from Arch Linux to Ubuntu and received errors as various executables weren't in the same places).

Is it possible to copy the
environment variable defined by the login shell into the current Bash script?

I see that my question has caused some confusion resulting in some thinking that I want to change the
environment variable of the login shell with a bash script, which is the exact opposite of what I want.

This is what I currently have at the top of one of my Bash scripts:

# Test if an internet connection is present
wget -O /dev/null google.com

I want to replace that second line with something that copies the value of
from the login shell into the script environment:

PATH=$(command that copies value of PATH from login shell)
# Test if an internet connection is present
wget -O /dev/null google.com

EDIT 2: Sorry for the big omission on my part. I forgot to mention that the scripts in question are being run on a schedule through cron. Cron creates it's own environment for running the scripts which does not use the environment variables of the login shell or modify them. I just tried running the following script in cron:

echo $PATH >> /home/user/output.txt

The result is as follows. As you can see, the
variable used by cron is different to the login shell:

user@ubuntu_router:~$ cat output.txt
user@ubuntu_router:~$ echo $PATH

Answer Source

After so long, I finally found the answer to this question:

PATH=$PATH:$(grep 'PATH=' /etc/environment | sed 's/^.*=// ; s/\"//g')

This command will grab the value assigned to PATH by Linux from the environment file and append it to the PATH used by Cron.

I used the following resources to help find the answer:

grep for contents AFTER pattern


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download