Warm tip: This article is reproduced from stackoverflow.com, please click
awk bash sed

BASH: use custom variable to update PATH

发布于 2020-04-11 22:03:39

I am trying to write a simple bash script that checks the output of command:whereis ls stores the relevant directory in a variable, in this case:

myvar=$(whereis ls | awk '{sub(/\/ls$/, "", $2); print $2}')
echo $myvar
$ /bin

Now using myvar I need to remove this directory from PATH and update PATH to reflect this change. How can I most efficiently accomplish this task?

Questioner
Jay Wehrman
Viewed
47
sergio 2020-02-02 11:43

You could use a pattern substitution ${parameter/pattern/string} to update PATH:

PATH=${PATH/#$myvar:/:}
PATH=${PATH/%$myvar/:}
PATH=${PATH/:$myvar:/:}

For example:

$ echo $PATH
/bin:xxx:/bin:yyy:/usr/sbin:zzz:/bin

$ echo $myvar
/bin

PATH=${PATH/#$myvar:/:}   # remove $myvar at the beginning of $PATH
PATH=${PATH/%$myvar/:}    # remove $myvar at the end of $PATH
PATH=${PATH/:$myvar:/:}   # remove $myvar anywhere else in $PATH

$ echo $PATH
:xxx:yyy:/usr/sbin:zzz::

Alternatively you could use sed:

$ echo $PATH
/bin:xxx:/bin:yyy:/usr/sbin:zzz:/bin
$ PATH=$(sed -E "s@(:|^)$myvar(:|$)@:@g" <<< $PATH)
$ echo $PATH
:xxx:yyy:/usr/sbin:zzz: