cioro_milano cioro_milano - 1 year ago 98
Bash Question

How can I delete a specific variable from my PATH environment variable using fish shell

Given an input variable say usr/bin and the following PATH

echo $PATH
/usr/local/bin /usr/bin /bin /usr/sbin /sbin /usr/local/sbin /Developer/bin

how can I write (in fish shell) a function that given the string/input can delete that path from my PATH variable?
->Ideally one that deletes the first occurrence (vs one that deletes all occurrences of such variable)

I was considering writing a small function such as

deleteFromPath usr/bin

Would it be better to write this in a scripting language like Perl/python/ruby rather than in fish shell?

for x in $list
if [ $x = $argv ]
//delete element x from list -> How?

Answer Source

This is rather easy to do in fish.

With set -e, you can erase not just entire variables, but also elements from lists, like set -e PATH[2] to delete the second element (fish counts list indices from 1).

With contains -i, you can find which index an element is at.

So you'll want to call set -e PATH[(contains -i $argv $PATH)].

With some error-handling and edgecases fixed, this'd look like

 function deleteFromPath
     # This only uses the first argument
     # if you want more, use a for-loop
     # Or you might want to error `if set -q argv[2]`
     # The "--" here is to protect from arguments or $PATH components that start with "-"
     set -l index (contains -i -- $argv[1] $PATH)
     # If the contains call fails, it returns nothing, so $index will have no elements
     # (all variables in fish are lists)
     if set -q index[1]
         set -e PATH[$index]
         return 1

Note that this compares the path strings, so you'd need to call deleteFromPath /usr/bin, with the leading "/". Otherwise it would not find the component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download