Monday, April 29, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 2184  / 3 Years ago, wed, october 13, 2021, 12:40:42

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?






More From » command-line

 Answers
4

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.


[#7215] Thursday, October 14, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
otatorm

Total Points: 218
Total Questions: 113
Total Answers: 124

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;