Search code examples
shellfish

Can I make an alias for `set -l` in the fish shell?


I make liberal use of set -l/set --local in my fish scripts, so I considered making an alias for it. The name local seems apt. Unfortunately, the obvious approach doesn't work:

function local
  set -l $argv
end

This fails because, of course, the variable this creates is local to the local function itself. Using alias doesn't work, either, since it's just a (perhaps legacy) shorthand for the above function.

Is there any way I can create a local variable in the calling scope without doing anything more complicated than local foo 'bar'? Obviously I could make something like eval (local foo 'bar') work, but that would sort of defeat the purpose. I'm open to any sort of trickery or hacks that would make this work, if any exist.


Solution

  • I'm afraid not, local variables are always local to the topmost scope, and there's no way to wrap set without creating a new scope. The best you can do is this:

    function def --no-scope-shadowing
        set $argv 
    end
    

    This creates a variable in the calling function scope. This is subtly different than local: local is scoped to a block, while the above is scoped to the function. Still it may be sufficient for your use case.