Update: Unsurprisingly, there is disagreement with this take. (I was sort of hoping for that.)
On the contrary, appending ensures that the system versions of utilities don't get shadowed. If some jerk does
— Tim Chase (@gumnos) October 6, 2023
$ ln -s /bin/rm ~/bin/cat
I'm sunk if I
$ PATH="$HOME/bin:$PATH"
$ cat important.txt
but if it's appended, I'm safe:
$ PATH="$PATH:$HOME/bin"
$ cat important.txt
There is never a good reason to do this. This is not only bad advice, it’s incredibly dangerous.
— unix-ninja (@unix_ninja) October 7, 2023
I wrote about that here:https://t.co/1GMFJOK5Sd
I’ll update this with a link to a new post once I’ve figured out how to incorporate these concerns.
For now, after reconsideration, I’ll say appending is generally safer and preferred absent a compelling reason to prepend.
So, take the following advice with a huge grain of salt.
Add directories to the beginning, not end, of the shell’s PATH
variable.
Don’t do this:
PATH=$PATH:~/bin
Do this:
PATH=~/bin:$PATH
Interactive demo
It’s easy to demonstrate the difference between prepending and appending PATH
interactively.
Don’t worry. Messing with the PATH
interactively doesn’t have any effect on your shell’s settings. It only affects the current shell.
If you’re not using zsh, substitute echo
for the print
commands below.
First, create and navigate to an experimental bin
directory. It can be located anywhere as long as the directory isn’t already included in PATH
:
mkdir ~/sandbox/bin
cd ~/sandbox/bin
Create a command named cat
:
% cat << EOF > ./cat
> #! /bin/zsh
> print meow
> EOF
% chmod +x ./cat
% ./cat
meow
Try #! /bin/sh
and echo
instead of print
if zsh isn’t installed on your system.
Append
Add the current directory to the end of PATH
:
% oldpath=$PATH # save current PATH setting
% PATH=$PATH:$(pwd) # add current dir to end of PATH
% cat cat
#! /bin/zsh
print meow
% PATH=$oldpath # restore original PATH
The shell used the system’s cat
command, not the one in the current directory.
Prepend
Now, try adding the directory to the beginning of PATH
:
% PATH=$(pwd):$PATH # add this dir to beginning of PATH
% cat cat
meow
The cat
command from the current directory was used, overriding the builtin command.
Don’t append
On macOS the default PATH
begins with /usr/local/bin
, allowing commands installed there to override builtin commands.
Commands added to PATH
should always override system commands, not the other way around.
Likewise, that’s how user directories should be added to PATH
, at the beginning.