1

I have created a shell script that will check if a certain value is existing in PATH. If not, then it will add that value to the PATH environment variable.

It was successfully added, based on the echo $PATH run inside the shell script. But when I tried to run echo $PATH in command line.. it does not reflect the changes made.

Here is my code:

#!/bin/bash
postgresPath="/opt/PostgreSQL/9.2/bin"
echo "Checking PATH env.."
[[ ":$PATH:" != *"$postgresPath"* ]] && export PATH="${PATH}:$postgresPath"
echo $PATH

http://rextester.com/RBLTT17164

1

2 Answers 2

5

The script runs in its own environment. It can not affect the environment of its parent shell (from which you start the script), i.e. changing $PATH in a script won't change $PATH in your interactive shell.

A mini-example of this:

$ echo "$PATH"
/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin

$ ( PATH="hello"; echo "$PATH" )
hello

$ echo "$PATH"
/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin

(it does not matter if I export the PATH variable again in the subshell since it's already exported)

I suggest either sourcing the script with . or source, which would execute the commands therein in the same environment as the current shell, or turning the script into a shell function.

2
  • ok thanks, I get it now.. but still, my shell script will recognize the modified env PATH, right? only inside the script..
    – john1717
    Sep 27, 2017 at 11:44
  • @john1717 Yes. The script itself will execute with the modified $PATH, and any processes it start will have the modified $PATH, but it won't be propagated back to the parent shell.
    – Kusalananda
    Sep 27, 2017 at 12:26
0

To Overcome the issue, I have added this into my

~/.bash_aliases

The below line and tested, working as expected.

function ep () { [ -n "$1" ] && DIR=$(readlink -fq $1) || DIR=$PWD; echo -e "exporting PATH (\e[33m$DIR\e[m)"; PATH=$DIR:$PATH; } 

Usage:

bashSHELL$ ep
or
bashSHELL$ ep /path/to/dir
or
bashSHELL$ ep ../path/to/dir
etc.

1
  • After adding the line, we need to start a new bash or restart the terminal.
    – Dipankar
    Jul 25, 2019 at 7:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .