0
votes

I have my path

~/desktop/Ruby » echo $PATH

and the result

/Users/zhang/.rvm/gems/ruby-2.1.2/bin:/Users/zhang/.rvm/gems/ruby-2.1.2@global/bin:/Users/zhang/.rvm/rubies/ruby-2.1.2/bin:/usr/local/bin:/usr/local/bin:/Users/zhang/.rvm/gems/ruby-2.1.2/bin:/Users/zhang/.rvm/gems/ruby-2.1.2@global/bin:/Users/zhang/.rvm/rubies/ruby-2.1.2/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin:/usr/local/git/bin:/usr/local/MacGPG2/bin:/Users/zhang/.rvm/bin:/Users/zhang/.rvm/bin:/Users/zhang/.rvm/bin

Here i have lots of redundancies in the path, perhaps I've something like “PATH=$PATH:.....” in my bash, but i didn't find it..

So
1. How can i delete redundant environment variables in macOS?
2. how can i make sure environement viriable without the repeats when i add the path?
3. how can i make the redundant path appear just one time?

2
@Max I'm intrigued - under what circumstances could it be good to repeat?Mark Setchell
You may not be aware of /etc/paths which also sets your PATH.Mark Setchell
well, i care about i because i'm a virgo..haha. i'm also in confuse in which condition could it be good to repeat. @MaxTuo

2 Answers

0
votes

How can I eliminate existing duplicates?

With some standard Unix tools (most of which I hope are readily available on OS X), you can eliminate duplicates like this. Note that some of these tools may work slightly differently on OS X, but these commands should work with minor tweaks. I have only tested on Linux because I do not have access to OS X at the moment.

PATH=`echo $PATH | sed 's/:/\n/g' | sort | uniq | paste -s --delimiters=":"`

This has the unfortunate side effect of sorting your PATH which may be undesirable if you have multiple versions of the same binary in different parts of your PATH.

In order to avoid this side effect, we can borrow a trick from this answer to do uniq without sort.

PATH=`echo $PATH | sed 's/:/\n/g' | awk ' !x[$0]++' | paste -s --delimiters=":"`

How can I avoid adding redundant paths to the PATH variable?

Use one of the many answers for String contains in bash to check whether PATH already includes the path you are about to add.

if [[ $PATH != *newpath* ]]
then
   export PATH=$PATH:newpath
fi
0
votes

The last line from my own $HOME/.profile file:

eval $(perl -e 'printf qq{export %s="%s";}, $_, join(":", grep { -d $_ && !$seen{ $_ }++ } split /:/, $ENV{$_}), $_ for( qw(PATH MANPATH) );')

It:

  • cleans up the environment variables PATH and MANPATH as
    • removes duplicates
    • removes nonexistent directories
  • creates the new export PATH="... cleaned up path ..."
  • reinitialise the new PATH a MANPATH

for the test: replace the eval with echo to show, what is doing exactly