I am new to Ubuntu.
I wrote a script to add a dir to the PATH environment. When I run the script it runs fine and the dir is added to the PATH. But it seems that the change only lasts until the script exits instead of lasting for the length of the session. When I look at the PATH after the script is ran the dir is no longer there. Any suggestions?
Best Answer
There's two things to remember:
Commands, including scripts, keep their environment for the duration of the command running
Commands inherit environment from parent process. For commands started via shell, they'll inherit from the shell.
So if you do
PATH=$PATH:/my/dir
that'll last only for the scripts duration. To make it permanent, the parent shell needs to be aware of the change. Proper way to do that would be to write to~/.bashrc
if you're using bash or appropriate rc file for your shell. Thus we can use >> to append to fileAnd when the script exits, run
so that the shell rereads the config and will be aware of the changes. Now every command you run in shell and every new interactive shell started will inherit new PATH variable
The two steps can be put together into a function since ( at least for bash ) functions run in current shell environment, so unlike a script when you do
source
part, callingsource
from a function will affect the current shell.