Found this question when trying to achieve this myself, and working from @geirha's answer, I got the following to work:
#!/usr/bin/env bash
# "thisfile" contains full path to this script
thisfile=$(readlink -ne "${BASH_SOURCE[0]}")
# the function to timeout
func1()
{
echo "this is func1";
sleep 60
}
### MAIN ###
# only execute 'main' if this file is not being source
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
#timeout func1 after 2 sec, even though it will sleep for 60 sec
timeout 2 bash -c "source $thisfile && func1"
fi
Since timeout
executes the command its given in a new shell, the trick was getting that subshell environment to source the script to inherit the function you want to run. The second trick was to make it somewhat readable..., which led to the thisfile
variable.