Sunday, May 31, 2009

Remove a path from $PATH variable in bash


$PATH on my ubuntu:

$ echo $PATH
o/p:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/org/bin:/opt/appls


Now to remove any path which contain "/org/" from PATH variable:

$ echo $PATH | tr ':' '\n' | awk '$0 !~ "/org/"' | paste -sd:
o/p:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/appls

Export the above to PATH

$ export PATH=$(echo $PATH | tr ':' '\n' | awk '$0 !~ "/org/"' | paste -sd:)
$ echo $PATH
o/p:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/appls

Use
awk '$0 != "/usr/local/sbin"'
in the above export awk part if you exactly want to remove the path "/usr/local/sbin" from PATH.

And using bash array:

$ echo $PATH
o/p:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/org/bin:/opt/appl

Remove any path which contain "/org/" from PATH

The one liner:
$ PATH=$(IFS=':';p=($PATH);unset IFS;p=(${p[@]%%*/org/*});IFS=':';echo "${p[*]}";unset IFS)

$ echo $PATH
o/p:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/appl

5 comments:

Adithya Kiran said...

Hi Jadu,

Here is one more interesting tip..

Some times, you are working on some long path say /home/a/b/c/d/e/f on tty1 and you navigated to tty2 and logged in. As soon as you login you may notice that you are in /root (in case of root user) and you may need to type full long path every time you login to tty2 and other ttys.

To fix this problem, add a below line in /root/.bash_profile

cd /home/a/b/c/d/e/f


And from now on, whenever you login to any tty, your starting path is /home/a/b/c/d/e/f

Done..!

Kevin Buchs said...

Here is a pure-bash way to do PATH manipulations. In this example, I remove redundant entries.

#!/bin/bash
IFS=":" pathstr=`eval echo $PATH`
IFS=" "
result=""
found=""
for a in $pathstr; do
wasfound=0;
for f in $found; do
if [ "$f" = "$a" ]; then
wasfound=1;
fi;
done;
if (( $wasfound != 1 )); then
found="$found $a";
result="${result}:${a}";
fi;
done
echo $result

Put this into pathmin.sh as an executable script in your path. Then you can do this assignment:
PATH=`pathmin.sh`

Anubis said...

I solved it like that:

export PATH= $(echo $PATH | tr ':' '\n' | awk '!/matching string/' | paste -sd:)

Jadu Saikia said...

@Anubis, thanks for the solution.
Correcting one typo: the space before $ is to be removed. Thanks again.

Võ Cảnh Bá Kha said...

echo $PATH

copy output then remove wrong dir.

export PATH=[paste]

© Jadu Saikia www.UNIXCL.com