0

I wanted to remove a CUDA directory from PATH by a sh script. The directories are showed by doing echo $PATH

/usr/local/cuda-9.0/bin:/usr/sbin:/usr/bin:

I want only:

/usr/sbin:/usr/bin:

My script changes nothing but it DOES in terminal(this script will be automatically executed when I do conda deactivate):

export PATH=$(echo ${PATH} | sed -r 's|/usr/local/cuda-9.0/bin||')

Could somebody tell me why and correct it into an elegant way?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

1
export PATH=$(echo ${PATH} | sed -r 's|/usr/local/cuda-9.0/bin||')

Or its more correct version:

export PATH="$(printf '%s\n' "$PATH" | sed 's|/usr/local/cuda-9\.0/bin||')"

Updates the content of the $PATH variable of the shell invoking that command by removing the first occurrence of /usr/local/cuda-9.0/bin in it. For instance, it would change a /bin:/opt/usr/local/cuda-9.0/bin/v2:/usr/local/cuda-9.0/bin to /bin:/opt/v2:/usr/local/cuda-9.0/bin which is not what you want.

To remove full elements, you could do:

export PATH="$(
  printf ':%s:\n' "$PATH" |
    sed '
      :1
      s|:/usr/local/cuda-9\.0/bin:|:|g; t1
      s|^:||; s|:$|'
)"

Or with zsh:

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

Note that if $PATH initially only contained /usr/local/cuda-9.0/bin, then the end result will be an empty $PATH. And empty $PATH means search for executables in the current directory which is not what you want. If that is a possibility, then you may want to make $PATH something like /inexistent/to/disable/PATH/lookup.

Note that in any case, it only changes the $PATH variable of the shell that runs that code. If you wanted that to affect the $PATH variable of the shell that invokes that script, you'd need that shell to source (as with the . or source command) that deactivate script, or make deactivate a function of that shell.

Or alternatively, you can have the deactivate script output the shell code that would be needed to remove those entries from $PATH (for instance by adding export -p PATH after having modified it) and make sure to invoke it as:

eval "$(deactivate)"

Within the shell where you want that entry to be removed from $PATH.

Something like:

#! /bin/zsh -
path=("${path[@]:#/usr/local/cuda-9.0/bin}")
export -p PATH
0

You could simply export PATH=/usr/sbin:/usr/bin. But your method already works:

$ PATH=/usr/local/cuda-9.0/bin:/usr/sbin:/usr/bin:
$ export PATH=$(echo ${PATH} | sed -r 's|/usr/local/cuda-9.0/bin||')
$ echo $PATH
:/usr/sbin:/usr/bin:

Trying to set PATH within your current environment by running a script is not possible.

l0b0
  • 51,350