Fix Duplicate $PATH Entries in Zsh with Oh My Zsh
When using Zsh with Oh My Zsh, you may notice repeated entries like:
This happens because multiple files append to $PATH without checking first. Here's how to fix it properly.
π Step 1: Understand What's Adding to $PATH
Zsh with Oh My Zsh can add to $PATH from:
~/.zshrc~/.zprofile~/.zshenv~/.oh-my-zsh/lib/path.zsh- Plugins or system-wide files (
/etc/zsh/zshenv,/etc/profile)
β
Step 2: Deduplicate $PATH Automatically
Zsh stores $PATH as an array called path.
At the **top of your .zshrc file, add:
This makes the path array unique, keeping $PATH clean.
π Step 3: Check and Remove Redundant Path Additions
Run this command to find where .local/bin or other paths are being added:
If you see export PATH="$HOME/.local/bin:$PATH" in more than one file, delete it from all but one β ideally keep it in ~/.zshrc.
β¨ Step 4: Use Zsh Arrays for Clean Path Management
Instead of modifying $PATH as a string, do this:
[[ "$path" != *"$HOME/.local/bin"* ]] && path+=("$HOME/.local/bin")
[[ "$path" != *"/snap/bin"* ]] && path+=("/snap/bin")
This safely appends to the path array only if not already present.
π Step 5: Verify It Works
- Restart your terminal
- Run this:
You should now see only one line per path β no duplicates.
Or use this Zsh-friendly function:
path() {
if [[ -n "$1" ]]; then
for p in "${path[@]}"; do
[[ "$p" == *"$1"* ]] && echo "$p"
done
else
for p in "${path[@]}"; do
echo "$p"
done
fi
}
π Sample .zshrc Snippet
Hereβs what your path section might look like:
# Deduplicate PATH
typeset -U path PATH
# Append paths safely
[[ "$path" != *"$HOME/.local/bin"* ]] && path+=("$HOME/.local/bin")
[[ "$path" != *"/snap/bin"* ]] && path+=("/snap/bin")
# Oh My Zsh setup
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="robbyrussell"
plugins=(git)
source $ZSH/oh-my-zsh.sh
β You're Done!
Zsh will now keep your $PATH clean, no matter how many times you open a terminal. π