XXWang XXWang - 4 months ago 6
Bash Question

delete substring from env variable doesn't work in shell

I was trying to delete a path from my PATH variable using the shell string manipulation approach: ${string%$substring}. It works for common variable but it doesn't work when I want to delete a path in PATH variable.

xiangxue➜~» echo $PATH [10:34:16]
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/xiangxue/anaconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin


Suppose I would like to delete :/usr/games entry from PATH, I did this:

xiangxue➜~» echo ${PATH%:/usr/games} [10:40:12]
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/xiangxue/anaconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin


The PATH doesn't delete :/usr/games entry, and it looks exactly same.

Answer

The ${parameter%pattern} string manipulation removes from the end of the string (see the Bash Guide on Parameter Expansion or the Bash Reference manual or the POSIX Spec) but :/usr/games isn't at the end of your string so it doesn't match.

The expansion you want for this is the ${parameter/pat/string} expansion:

echo "${PATH/:\/usr\/games}"

Alternatively you want to split $PATH on : and loop to filter out your desired entry.