Where is the function declaration in bash?
There are many libs included in my script in bash and I am using the functions declared in those files. Like this:
#!/bin/bash
. foo.inc
. bar.inc
. baz.inc
function_1
function_2
function_3
EOF
My question is, how do I know which file includes function_1 declaration? During the execution of this script.
Edit:
Add the following line to your script:
shopt -s extdebug
then you can get the original filename and line number in that file where the function definition starts:
def=($(declare -F function_1))
echo "function name: ${def[0]}"
echo "line number: ${def[1]}"
echo "file name: ${def[@]:2}" # the array slice makes it work even if the filename contains spaces
Original answer:
At runtime, you don't need to know which file provided the function. Perhaps if you post your code we could better understand what you need.
When you send a file (eg " . foo.inc
"), it is as if it were in the main file.
If you need, for some reason, to find out if it is still loaded, you can do something ugly (akin to children in a car crying "are we still there?" 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 the functions listed in $function_list
, and if it finds them, echo them and remove them from the list. (Say it quickly three times!)
Edit
Here's a way to do what I think might be very close to what you want:
In each of your functions, add a test for the 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 list the files containing the functions and find the source of the specific function:
function_1 --source
will display the filename from which it was retrieved. And, of course, you can act on this:
if [[ $(function_1 --source) == /some/dir/file ]]
then
do_something
fi
source to share