I'm trying to figure out how I can load changes to my .bash_profile
without having to logout of my Bash session or exit Terminal, also without affecting my $PATH
.
In a new session this is my $PATH
:
/Users/MyName/.rbenv/shims:/usr/local/heroku/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/local/go/bin
And this is the alias I setup to reload my .bash_profile
:
alias reload='source ~/.bash_profile'
When I run the reload
command, my changes to my .bash_profile
are loaded, but my $PATH
is lengthened with each time I run the command.
For example:
>> reload
>> echo $PATH
/Users/MyName/.rbenv/shims:/usr/local/heroku/bin:/usr/local/bin:/Users/MyName/.rbenv/shims:/usr/local/heroku/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/local/go/bin
As you can see my $PATH
is now longer and I think this is because the following is in my .bash_profile
:
export PATH="/usr/local/bin:$PATH"
export PATH="/usr/local/heroku/bin:$PATH"
How can I keep my $PATH
from being updated with each reload?
Okay, trick number one: You reload a script like .bash_profile using
$ source .bash_profile
The source built-in reads a shell script as if it were coming from standard input, instead of forking a sub shell.
Trick number two: That assignment
PATH=/my/new/path:$PATH
is just appending what was already in PATH to the new string. So, it's like doing
PATH=/my/new/path:my/old/path/:/my/even/older/path
You don't like that behavior, you just reset PATH first. What I do is like this:
PATH=
PATH=/bin:$PATH
PATH=/usr/bin:$PATH
and so on. Now the path will be exactly what you expect.
Update
Here's exactly how my file looks:
export PATH=
export PATH=/bin
export PATH=${PATH}:/sbin
export PATH=${PATH}:/usr/local/bin
export PATH=${PATH}:/usr/sbin
export PATH=${PATH}:/usr/bin
export PATH=${PATH}:/usr/local/opt/go/libexec/bin
the exports
aren't really important, as PATH
is already exported, they're just me being fastidious.
You can also look at this answer for some of the rest of how I set up my shell: About .bash_profile, .bashrc, and where should alias be written in?
You should look at the Bash Guide for Beginners, there's lots of useful stuff there.
Or, you can check before inserting or appending to PATH if the value is not there already:
insert_to_path()
{
if [[ "$PATH" =~ (^|:)"${1}"(:|$) ]]
then
return 0
fi
export PATH=${1}:$PATH
}
insert_to_path /usr/local/bin
insert_to_path /usr/local/heroku/bin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With