Clean Path Manipulations

For Bash, these let you screw around with $PATH without getting, um, pathologically weird contents.

# Remove (an) entry(ies) from PATH
pathdel() {
 for remove in "$@"
 do
 IFS=: read -r -a path <<< "$PATH"
 for i in "${!path[@]}"
 do
 if fgrep "$remove" -- - <<< "${path[$i]}"
 then
 unset path[$i]
 fi
 done
 export PATH=$(IFS=: ;echo "${path[*]}")
 done
}

# Preface PATH with (an) entry(ies)
pathadd() {
 declare -A seen
 IFS=: read -r -a path <<< "$PATH"
 for dir in "$@"
 do
 seen[$dir]=t
 done
 for i in "${path[@]}"
 do
 seen[$i]=t
 done
 export PATH=$(IFS=:; echo "${!seen[*]}")
}

# Clean out duplicate PATH entries
pathclean() {
 declare -A seen
 IFS=: read -r -a path <<< "$PATH"
 for i in "${path[@]}"
 do
    seen[$i]=t
 done
 export PATH=$(IFS=:; echo "${!seen[*]}")
}

 

What do you think? Add your comments →