Update: Unsurprisingly, there is disagreement with this take. (I was sort of hoping for that.)

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.

:x: Don’t do this:

PATH=$PATH:~/bin

:heavy_check_mark: 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.

Categories:

Published: