[SOLVED] How to define a function's body from a file in bash?

Issue

I have a plugin manager and it’s kinda
inefficient with functions and I want
to make it more efficient but I can’t find
a good way to load them

Currently it just makes the function source
the function body like this:

__baz_load_functions() {
    _func_dir="$plugin/$BAZP_SRC/functions"

    if [ -d "$_func_dir" ]; then
        for _baz_func in "$_func_dir"/*; do
            [ ! -f "$_baz_func" ] && continue
            _func_name="$(__baz_get_base "$_baz_func" | __baz_sanitize)"
            [ ! "$_func_name" ] && continue

            __baz_vecho "Loading function '$_func_name'"
            eval "function $_func_name() { source '$_baz_func'; }"
        done
    fi
}

And I tried using cat on the body and it just breaks
and I can’t really think of anything
else, maybe there’s a special keyword
or something to do that?

Solution

You can read the file contents into a variable, then use that in eval.

This is untested but I think it should work:

__baz_load_functions() {
    _func_dir="$plugin/$BAZP_SRC/functions"

    if [ -d "$_func_dir" ]; then
        for _baz_func in "$_func_dir"/*; do
            [ ! -f "$_baz_func" ] && continue
            _func_name="$(__baz_get_base "$_baz_func" | __baz_sanitize)"
            [ ! "$_func_name" ] && continue

            __baz_vecho "Loading function '$_func_name'"
            _baz_func_body=$(< "$_baz_func")
            eval "function $_func_name() { 
                $_baz_func_body
            }"
        done
    fi
}

However, your method has an interesting feature: You can edit a file in the functions directory, then calling the function will use the new version immediately, rather than having to reload it.

Answered By – Barmar

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.