2

Following advice from a course, I added the following line to my .bashrc:

export PATH=/home/dodgycoder/kafka_2.12-2.3.1/bin:$PATH

Now, when I open a terminal window I get this directory shown twice:

$ echo $PATH
/home/dodgycoder/kafka_2.12-2.3.1/bin:/home/dodgycoder/kafka_2.12-2.3.1/bin:/usr/local/bin:...

Why is this? What's the correct way to add a directory to your PATH?

I'm using Fedora with the Gnome desktop. I confirm I only have the above line just once in my .bashrc and it's not defined anywhere else.

2 Answers2

2

The issue you have here is the way you did add the PATH component.

When you add a directory to PATH, it could already be present. There are two options in that case : 1) Do not add it again, or 2) remove+add it.

I use the (2), as I prefer to control the directories order in PATH.

To avoid this problem, I use a couple of functions in my .bashrc, which allow to add a directory at beginning or end of PATH, keeping only one occurrence of it.

A way to define these functions could be :

# _remove $1 from PATH
_path_del() {
    local _l=":$PATH:"
    while [[ $_l =~ :$1: ]]; do
          _l=${_l//:$1:/:}
    done
    _l=${_l%:}
    _l=${_l#:}
    PATH="$_l"
}

_prepend : prepend $1 to PATH.

_path_prepend() { _path_del "$1" PATH="$1:$PATH" }

_append : append $1 to PATH.

_path_append() { _path_del "$1" PATH="$PATH:$1" }

Usage example :

# possible initial PATH
PATH=/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin

append ~/bin if it exists

[[ -d "$HOME/bin" ]] && _path_append "$HOME/bin" printf "%s\n" "$PATH"

prepend ~/bin if it exists

[[ -d "$HOME/bin" ]] && _path_prepend "$HOME/bin" printf "%s\n" "$PATH"

Output:

/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin:/home/br/bin
/home/br/bin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin

EDIT : If you don't care the order of new directory in PATH, and prefer the (slightly faster) solution (1), you could try something like :

[[ :$PATH: =~ :$newpath: ]] || PATH="$newpath:$PATH"  # prepend
[[ :$PATH: =~ :$newpath: ]] || PATH="$PATH:$newpath"  # append
Bruno
  • 180
0

.bashrc is not the best place to set $PATH or any other environment variable, since it may be invoked more than once.

Environment variables had better be set in ~/.profile.

See the following posts:

harrymc
  • 498,455