What is the most elegant way to remove a path from the $PATH variable in Bash? What is the most elegant way to remove a path from the $PATH variable in Bash? bash bash

What is the most elegant way to remove a path from the $PATH variable in Bash?


My dirty hack:

echo ${PATH} > t1vi t1export PATH=$(cat t1)


A minute with awk:

# Strip all paths with SDE in them.#export PATH=`echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}'`

Edit: It response to comments below:

$ export a="/a/b/c/d/e:/a/b/c/d/g/k/i:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i"$ echo ${a}/a/b/c/d/e:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i## Remove multiple (any directory with a: all of them)$ echo ${a} | awk -v RS=: -v ORS=: '/a/ {next} {print}'## Works fine all removed## Remove multiple including last two: (any directory with g)$ echo ${a} | awk -v RS=: -v ORS=: '/g/ {next} {print}'/a/b/c/d/e:/a/b/c/d/f:## Works fine: Again!

Edit in response to security problem: (that is not relevant to the question)

export PATH=$(echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}' | sed 's/:*$//')

This removes any trailing colons left by deleting the last entries, which would effectively add . to your path.


Since the big issue with substitution is the end cases, how about making the end cases no different to the other cases? If the path already had colons at the start and end, we could simply search for our desired string wrapped with colons. As it is, we can easily add those colons and remove them afterwards.

# PATH => /bin:/opt/a dir/bin:/sbinWORK=:$PATH:# WORK => :/bin:/opt/a dir/bin:/sbin:REMOVE='/opt/a dir/bin'WORK=${WORK/:$REMOVE:/:}# WORK => :/bin:/sbin:WORK=${WORK%:}WORK=${WORK#:}PATH=$WORK# PATH => /bin:/sbin

Pure bash :).