1

Sometimes, usually when installing packages with brew, I want to disable/remove certain parts of my path, and then later restore them. I haven't been able to find an easy way to do this, and while I could write my own bash script to do so, I'm wondering if there's an easier way.

Desired behavior (or something like it):

$ echo $PATH
/Users/mchenja/anaconda/bin:/usr/local/bin:/(and so on)
$ changepath "brew"; echo $PATH
/usr/local/bin:/(and so on)
$ changepath "anaconda"; echo $PATH
/Users/mchenja/anaconda/bin:/usr/local/bin:/(and so on)

Here, "brew" and "anaconda" are just user-defined keywords to manipulate a saved path.

Does bash offer a built-in method of doing this? What about an external add-on?

0

3 Answers 3

0

Depending on how complicated your use-case actually is, you can set and/or change a variable for just one command by prefixing the command with the variable's value. For example,

1 prompt> X=1
2 prompt> X=2 some_command arg1 arg2
3 prompt> echo $X

the variable X will be 2 inside some_command, but returned back to X=1 on line 3. So you could temporarily change the PATH for just one command to strip out the matching prefix string (assuming your requirement is as simple as this), e.g.,

1 prompt> PATH=${PATH#/Users*:} brew ...args...

This will strip from the PATH the prefix starting with "/Users" ending at the first ":". E.g., instead of /Users/foo/bar:/usr/bin/.... you'll just have /usr/bin/..... Whether this is easier than aliases is questionable, but it could be incorporated into your aliases/functions/scripts. Main advantage is that it dynamically modifies your PATH from whatever it's currently set to; but that's the main disadvantage, as well :-)

3

Swapping the contents of a variable is like the easiest thing to do in any language. There's no special facility in bash for swapping the contents of the PATH variable because swapping the contents of any variable is so darn easy to do.

For example, you could add this to the end of your favorite shell startup script:

DEFAULTPATH="$PATH"
alias dp="PATH=\"$DEFAULTPATH\""
alias ap="PATH=\"/Users/mchenja/anaconda/bin:$DEFAULTPATH\""
alias bp="PATH=\"/usr/local/bin:$DEFAULTPATH\""

Now, at runtime, you can just type ap, bp, or dp to switch between your anaconda, brew, and default PATHs, respectively.

1

Create individual files with the desired PATH variable and store them in a directory in your home folder. Example:

cat ~/ch_path.d/brew

PATH="/usr/local/bin:/(and so on)"
export PATH

Then you can source whatever path you want

source ~/ch_path.d/brew

You must log in to answer this question.