Over a million developers have joined DZone.

Add A Folder To PATH, But Not If It Is Already In PATH

DZone's Guide to

Add A Folder To PATH, But Not If It Is Already In PATH

Free Resource
Often times one uses a single .profile or .bashrc across several hosts.  These hosts may be differently configured, with varying directory locations, and different initial PATH values from /etc/profile.  In situations like this, setting PATH the traditional way -- "PATH=$PATH:/path/to/some/stuff" -- can result in a cumbersomely long PATH that includes inaccessible or duplicate folders.  

The snippet below nicely handles this problem.  It has been tested on Solaris and Linux.

AddPath ()
# Add argument to $PATH if:
# - it is not already present
# - it is a directory
# - we have execute permission on it
# This snippet is public domain; you may use it freely.  Death to copyright, patents, 
# and all other forms of intellectual monopoly.  
  echo " $PATH " | sed 's/:/ /g' | grep " $_folder " > /dev/null
  [ $? -ne 0 ] && [ -d $_folder ] && [ -x $_folder ] && PATH=$PATH:$_folder
  export PATH

# Add some common paths:
AddPath /usr/bin
AddPath /usr/local/bin
AddPath /opt/somepackage/bin


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}