fox
fox

Reputation: 16486

how to dynamically add to $PATH on Linux / OS X

I know that in order to add a directory to my OS X path, I'm supposed to edit my ~/.bashrc or ~/.profile file to add something like:

export PATH=<<somepath>>:$PATH

I'm pretty new to bash and was wondering: would it be possible to edit, for instance, my ~/.bash_profile file so that I could do this dynamically, so that from the command line I could permanently add a directory to my path by doing something like

addpath <<somepath>>

instead?

Upvotes: 0

Views: 1707

Answers (2)

MrBooks
MrBooks

Reputation: 60

Needing to add entries to your path is pretty rare... so it seems excessive to create a script just for that. But if you want to do keep from manually editing the file you can use the following script:

  #!/bin/bash

  sed -i "s/PATH=/PATH=$1:/" .bash_profile

once you create the file set it to execute using

chmod u+x <script name>

Upvotes: 0

user3132310
user3132310

Reputation:

First create an empty file in your home directory, this file will be a place to collect all the new additions to your path, so

touch ~/.build_path

Next you need to ensure that all your new path additions are processed when your ~/.bashrc file is processed, so add this line to your ~/.bashrc file:

source ~/.build_path

Finally, add this function into your ~/.bashrc file, this function makes an immediate change to the current PATH setting, and adds a new entry to the ~/.build_path file so that future shells will pick up the new path.

function addpath
{
    echo "export PATH=\"$1\":\${PATH}" >> ~/.build_path
    export PATH=$1:$PATH
}

That should pretty much do it. The only obvious problem is that if you have two running shells changing the path in one shell will not cause the path in the second to be updated, you'd need to restart the second shell.

Upvotes: 2

Related Questions