0

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

4

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.

  • 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 '17 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 '17 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.