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
while read -r line; do
    if [[ ! -z "${line// }" ]] && [[ "$line" != \#* ]]; then
	line=$(echo "$line" | envsubst) 
        if [[ -d "$line" ]] && [[ p["$line"] -ne "1" ]]; then
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
# Duplicates will be added only once
# Pathes that do not point to a valid directory will be ignored
# Pathes that already exist will be ignored

Possible resulting path:

$ echo $PATH