Building a portable $PATH

I reg­u­larly swap between sev­eral dif­fer­ent Linux in­stances, which all share a com­mon shell con­fig­ur­a­tion file. One of my pet nuis­ances is that the $PATH vari­able ends up swell­ing in size to ac­com­mod­ate for all of the setup-spe­cific dir­ect­or­ies for bin­ar­ies, lead­ing to a bloated vari­able full of dir­ect­or­ies which may not even ex­ist on the spe­cific ma­chine.

I had a few minutes to burn today so I wrote a small snip­pet for my .bashrc that al­lows me to main­tain a list of all the de­sired PATH dir­ect­or­ies which are then ad­ded on an as-needed basis, only if the dir­ect­ory ex­ists on the cur­rent sys­tem:

# The list of directories to add to the path. Directories
# are added sequentially from first to last. A directory
# is only added if it exists.
path_dirs=( \
            ~/bin \
            ~/.local/bin \
            ~/emacs/bin \
            ~/android-sdks/platform-tools \
            /usr/lib/ccache \
            /usr/local/bin \
            /usr/contrib/bin \
            /opt/bin \
            /bin \
            /usr/bin \
            /usr/local/games \
            /usr/games \
            )

# Build path from directory list
unset PATH
for d in "${path_dirs[@]}"; do
  test -d $d && PATH=$PATH:$d
done

# Strip the leading ':' from the path
export PATH=${PATH:1}

# Respect the environment
unset path_dirs

Lovely, now I have a neat and tidy PATH once again. Why did­n’t I fix this be­fore?

07 Aug 2013