About Blog Contact

Load PATH from File: No More Messy Appends

The end of my .bashrc file is getting messy. It is filled with export statements, prepending and append pathes into my environment variable PATH. Not only it’s hard to read, it is difficult for me to reorder the path locations. So I wrote a script to load pathes from ~/.bash_path file. Just put the following snippet at the end of your .bashrc:

declare -A p
for path in ${PATH//:/ }; do
    p["$path"]="1"
done
while read -r line; do
    if [[ ! -z "${line// }" ]] && [[ "$line" != \#* ]]; then
	line=$(echo "$line" | envsubst) 
        if [[ -d "$line" ]] && [[ p["$line"] -ne "1" ]]; then
	    p["$line"]="1"
	    PATH="$line:$PATH"
	fi;
    fi;
done < ~/.bash_path
export PATH="$PATH"

Then, create your .bash_path file and put your pathes there like this:

# This is a comment
# Environment variables are supported
$HOME/Scripts
# Duplicates will be added only once
$HOME/Duplicate
$HOME/Duplicate
# Pathes that do not point to a valid directory will be ignored
$HOME/NoneExistantPath
# Pathes that already exist will be ignored
/bin

Possible resulting path:

$ echo $PATH
/home/mengyibai/Duplicate:/home/mengyibai/Scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin