Ubuntu – How to add a directory to PATH in a script so that it affects the calling shell and the rest of the session

bashcommand lineenvironment-variablesscripts

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:

  1. Commands, including scripts, keep their environment for the duration of the command running

  2. 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 file

echo PATH=$PATH:/my/dir >> ~/.bashrc

And when the script exits, run

source ~/.bashrc

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, calling source from a function will affect the current shell.