0

How can I save a modified PATH in PATH_MOD that does not contain /usr/bin?

Output of PATH:

/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
roaima
  • 107,089
  • 14
  • 139
  • 261

2 Answers2

0

have you tried:
PATH_MOD=$(echo $PATH | sed 's/:\/usr\/bin:/:/g')

EDIT: double \ in order to make backslashes visible

  • 1
    That wouldn't work if `/usr/bin` was first or last in `$PATH` or if there were 2 consecutive `/usr/bin` (as in `PATH=/x:/usr/bin:/usr/bin:/y`) – Stéphane Chazelas May 29 '20 at 18:21
  • 1
    That would also potentially not work properly if `$PATH` contained `$IFS` characters or wildcards or backslashes or was something like `-Ennen`... – Stéphane Chazelas May 29 '20 at 18:35
0

In the zsh shell:

path=("${path[@]:#/usr/bin}")

updates $PATH in place. Or to set $PATH_MOD instead:

PATH_MOD=${(j[:])path:#/usr/bin}

In zsh, $PATH is tied to the $path array (like in (t)csh) and ${array:#pattern} expands to the elements of the array that don't match the pattern.

Beware that if $PATH was just /usr/bin, then it becomes empty. For zsh, that means there's no command to be found anywhere, but for most of everything else, that means the current working directory is looked for for commands!

The equivalent in bash 4.4+ could be done using some helper function like:

remove_element() {
  local - text=$1 IFS=$2 element=$3 i
  set -o noglob
  set -- $text""
  for i do
    if [ "$i" != "$element" ]; then
       set -- "$@" "$i"
    fi
    shift
  done
  REPLY="$*"
}

remove_element "$PATH" : /usr/bin
PATH_MOD=$REPLY
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501