2

I'm running Fish version 3.7.0, and I want to write a function to remove elements from lists, based on their index.

For instance, I want to remove the element from PATH environment variable at index 2:

set -l variable_name PATH
set -l index 2
set -e $variable_name[$index]

However, the follow statement does not work, it returns:

set: --erase: option requires an argument

I see it requires some lazy evaluation to get the variable name (e.g. PATH), but I didn't figure how to do that.

2
  • 1
    This should work: set -e {$variable_name}[$index] -- separate the indexing syntax from the expansion of the variable name. Commented Apr 16 at 15:22
  • @glennjackman Thank you! It works!!
    – uilianries
    Commented Apr 16 at 16:30

1 Answer 1

3

The issue is that fish takes $var[$foo] as "the footh element of $var", where you want "expand $var, expand $foo, and attach both together".

You can use a variety of ways to express what you want, the cleanest is probably:

set -e $variable_name[1][$index]

This will expand the first element of $variable_name ("PATH"), the other [] will not be syntactically special, so it will end up running

set -e PATH[2]

like you want.

Alternatives include quoting (set -e "$variable_name"[$index]), brace expansions (set -e {$variable_name}[$index]) - you really just need to separate the $var from the [$foo] part. Even setting index to [2] and using set -e $variable_name$index works.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .