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?
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: