There are a few things that it's nice to do when adding a directory pathsome situations where it using (which hereon I'll referPATH=/a/b:$PATH
might be considered the "incorrect" way to asadd a "dir" to avoid confusion)path to PATH
:
- Check to see that the dir isAdding a path that's not actually valid.
- Don't add a dir twicedirectory.
- Canonicalize the dir you're adding to ensure you're not adding an alias for an existing dirAdding a path that's already in
PATH
in the same form.1 - IfAdding a dir isrelative path (since the actual directory searched would change as you change the current working directory).
- Adding a path that's already in
PATH
but not at the frontin a different form (i.e., force itan alias due to using symlinks or..
). - If you avoid doing 4, not moving the frontpath to ensure the programs in that dir take priority over othersfront of the same name in
PATH
when it's intended to override other dirsentries inPATH
.
This (Bash-only) function does the "right thing" in the above situations (with an exception, see below), returns proper error codes, and prints nice messages for humans. (TheThe error codes and messages can be disabled when they're not wanted.)
1 Technically The exception is that this function does not canonicalize paths added to PATH
via other means, you also should be canonicalizing all existing directoriesso if a non-canonical alias for a path is in PATH
, but I've been too lazythis will add a duplicate. Trying to do thatcanonicalize paths already in PATH
is a dicey proposition since a relative path has an obvious meaning when passed to prepath
but when already in the code included herepath you don't know what the current working directory was when it was added.