views:

270

answers:

2

In my script in bash, there are lot of included libs and I use functions declared in these files. Like this:

#!/bin/bash
. foo.inc
. bar.inc
. baz.inc

function_1
function_2
function_3

EOF

My question is how to learn which file include function_1 declaration? In runtime of this script.

+1  A: 

You don't know. You'll have to grep the included files for the definition

Mark
I dont want to be dependent from includes...
Grokix
Then you must not include them. Sorry I don't understand your issue fully. If you include the files you depend on them
Mark
I don't want to add new grep, when I include new lib...type -t function_1 can tell that this is a functiontype -f ping can tell where is the fileMay be there is a way to learn in which file my function defined...?
Grokix
+1  A: 

You shouldn't need to know at runtime which file provided a function. Perhaps if you posted your code, we could better see what you need.

When you source a file (using ". foo.inc" for example), it's as if it were actually in the main file.

If you need, for some reason, to know if it's loaded yet, you could do something ugly (akin to kids in the car crying "are we there yet?" every few seconds):

function_check ()
{
    local fn found notfound;
    for fn in $function_list;
    do
        if [[ -n $(declare -F $fn) ]]; then
            found+=$fn" ";
        else
            notfound+=$fn" ";
        fi;
    done;
    echo $found;
    function_list=$notfound
}

function_list="function_1 function_2 function_3"

. foo.inc
foo_list=$(function_check)

. bar.inc
bar_list=$(function_check)

. baz.inc    
baz_list=$(function_check)

echo "Warning: the following functions were not found: $function_list"

The function function_check checks for the existence of functions listed in $function_list and if found echoes them and removes them from the list. (Say that fast three times!)

Edit:

Here's a way to do what I think may be very close to what you want:

In each of your functions, add a test for an option that returns its source like this:

function_1 ()
{
    if [[ $1 == "--source" ]]
    then
        echo "source: ${BASH_SOURCE}"
        return
    fi

    # do your function stuff
}

Then in your script, you can source the files containing the functions and to find the source of a particular function:

function_1 --source

will echo the filename it came from. And of course you can act on it:

if [[ $(function_1 --source) == /some/dir/file ]]
then
    do_something
fi
Dennis Williamson