2012-02-12 § 9 Comments
Calling all bash users. This is a public service announcement.
Here’s something you need to know if you want to write bash scripts that work reliably, but you probably don’t.
For script authors: Every bash script that uses the
cd command with a relative path needs to call
unset CDPATH, or else it may not work correctly. Scripts that don’t use
cd should probably do it anyway, in case someone puts a
cd in later.
For users: Never export CDPATH from your shell to the environment. If you use CDPATH then set it in your
.bashrc file and don’t export it, so that it’s only set in interactive shells.
For the bash implementers: Change bash to ignore the inherited value of CDPATH in shell scripts (as opposed to interactive shells).
Since I wrote this, thanks to commenters here and on Reddit I’ve learnt two interesting things:
- CDPATH is not a bash-specific feature; it’s actually specified by POSIX.
- You can avoid it in some cases by using
cd ./foo, which does not consult CDPATH. But this is not a panacea: it can’t easily be used with paths that might be absolute or relative, such as
`dirname "$0"`, so I think unsetting CDPATH is still the best way to deal with it.