XJDHDR XJDHDR - 1 month ago 4
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

PATH
environment variable. I recently discovered that this doesn't make the script very portable as the
PATH
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
PATH
environment variable defined by the login shell into the current Bash script?




EDIT:
I see that my question has caused some confusion resulting in some thinking that I want to change the
PATH
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:

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl
# 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
PATH
from the login shell into the script environment:

#!/bin/bash
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:

#!/bin/bash
echo $PATH >> /home/user/output.txt


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

user@ubuntu_router:~$ cat output.txt
/usr/bin:/bin
user@ubuntu_router:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

Answer

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

https://help.ubuntu.com/community/EnvironmentVariables#System-wide_environment_variables