Search code examples
functionshellsyntaxfish

In fish, what are the pros and cons of a function call versus sourcing a "partial" file?


Say for example you have a few different fish functions for scaffolding different types of projects, but within each you'd like to have a reusable block for running some git commands.

So you could create a separate function, and call it from the other functions, or you could take the separate function file, remove the function name -d "description" and end lines out of it, and then from the other functions just invoke it with source /path/to/partial.

So I'm wondering when a person should use one method instead of the other.


Solution

  • Using functions gives you a few advantages over sourcing a file:

    1. You can tab-complete function names, and add custom completions to tab-complete their arguments
    2. They can be modified using funced and funcsave
    3. There's a standard place for them in ~/.config/fish/functions
    4. They can be autoloaded.

    The one advantage of sourcing a file is that it can introduce variables into the caller's scope. For example, set var value inside a sourced file will be scoped to the caller's function. (Of course you can make the variable explicitly global from a function or a sourced file: set -g var value).