Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle duplicates in my PATH variable?

Tags:

bash

shell

path

I recently added this line to my .bashrc file so that I could use the java compiler javac from the command line (using MobaXTerm if that makes a difference)

export PATH=$PATH:"/cygdrive/c/Program Files/Java/jdk1.8.0_101/bin"

But I'm seeing multiple duplicates in my $PATH variable (note that the newlines were only added for readability)

/bin:
/drives/c/Users/Justin/DOCUME~1/MobaXterm/slash/bin:
/drives/c/WINDOWS:
/drives/c/WINDOWS/system32:
/cygdrive/c/ProgramFiles/Java/jdk1.8.0_101/bin:
/cygdrive/c/ProgramFiles/Java/jdk1.8.0_101/bin:
/cygdrive/c/ProgramFiles/Java/jdk1.8.0_101/bin

Is there something wrong with the way I'm adding to my $PATH?

like image 613
J-Win Avatar asked May 28 '17 21:05

J-Win


1 Answers

If PATH is manipulated by different scripts that are called by .bashrc, this is usually the result.

While duplicates in PATH aren't a major problem, there are two approaches to keeping PATH free of them:

  1. Check if a dir already exists in PATH before adding
  2. Dedupe PATH as the last step in your .bashrc

Check before adding

javabin="/cygdrive/c/ProgramFiles/Java/jdk1.8.0_101/bin"
if ! [[ $PATH =~ "$javabin" ]]; then
  PATH="$PATH:$javabin"
fi

or write a function:

add_to_path() {
    local dir re

    for dir; do
        re="(^$dir:|:$dir:|:$dir$)"
        if ! [[ $PATH =~ $re ]]; then
            PATH="$PATH:$dir"
        fi
    done
}

add_to_path "/cygdrive/c/ProgramFiles/Java/jdk1.8.0_101/bin"

Dedupe (the best method I found on SO)

PATH="$(perl -e 'print join(":", grep { not $seen{$_}++ } split(/:/, $ENV{PATH}))')"

See also on Unix & Linux / SuperUser StackExchange:

  • PATH is filled with duplicates
  • Remove duplicate $PATH entries with awk command
  • How to correctly add a path to PATH?
like image 141
codeforester Avatar answered Oct 02 '22 22:10

codeforester