Search code examples
shellexportfishdotfiles

How to export a function in fish shell


I'm porting some of my script from bash to fish shell, and fail to get access to my utilities functions.

Bash

Here is how I do it in bash, first declare my methods in "$HOME/.my-posixrc":

function configure_date_utilities() {
    function today() {
        to-lower "$(date '+%Y-%b-%d')"
    }
    function today-num() {
        to-lower "$(date '+%Y-%m-%d')"
    }
    function now() {
        to-lower "$(date '+%Y-%b-%d-%H:%M')"
    }
}

Then source this file :

source "$HOME/.my-posixrc"

So I can do:

$ today

2015-dec-13

Fish

function configure_date_utilities
    function today
        to-lower (date '+%Y-%b-%d')
    end
    function today-num
        to-lower (date '+%Y-%m-%d')
    end
    function now
        to-lower (date '+%Y-%b-%d-%H:%M')
    end
end

Then source this file in ~/.config/fish/config.fish:

source "$HOME/.my-posixrc"

But the methods aren't found:

$ today

The program 'today' is currently not installed. You can install it by typing: sudo apt-get install mhc-utils

Question

How do I "export" my function so I can access them in my prompt?

P.S.: my dotfiles are available on github.


Solution

  • Drop the outer function or call it in the file.

    In fish, all functions are global, but your inner functions won't be defined because their definition is never run.

    So either:

    function configure_date_utilities
        function today
            to-lower (date '+%Y-%b-%d')
        end
        function today-num
            to-lower (date '+%Y-%m-%d')
        end
        function now
            to-lower (date '+%Y-%b-%d-%H:%M')
        end
    end
    configure_date_utilities
    

    or

    function today
        to-lower (date '+%Y-%b-%d')
    end
    function today-num
        to-lower (date '+%Y-%m-%d')
    end
    function now
        to-lower (date '+%Y-%b-%d-%H:%M')
    end