Calling function from another bash script

I would like to call functions from another bash script. How can I do it?

 Some code More code  

Try "sourcing" the file :

. /path/to/file_containing_functions

dot - execute commands in the current environment

A simple example:

$ cat Add.fn
Add ()
{
    echo $(($1 + $2))
}
$
$ cat test.sh
#! /bin/bash
. ./Add.fn

Add 2 3
$
$ ./test.sh
5
$

I would also like to call some variables in the file but which are outside the function. Is that possible. For example, having some settings.

$ cat Add.fn
tst="Hello"
Add ()
{
    echo $(($1 + $2))
}
$
$ cat test.sh
#! /bin/bash
. ./Add.fn

echo "$tst"
Add 2 3
$
$ ./test.sh
5
$


That works too, just try it..

Works. I would need to get the path to the bash scripts directory though.

I put my scripts in the location

/home/tcdata/tatsh/trunk/hstmy/bin/bash

Then go to my test directory and do things as shown

cd /home/tcdata/tatsh/branches/test
/home/tcdata/tatsh/trunk/hstmy/bin/bash/tsimplex.bash        # run script

Need to get the path of the bash files. In tsimplex.bash I need to capture the string path in the calling sequence of tsimplex.bash.

/home/tcdata/tatsh/trunk/hstmy/bin/bash

What is the way to achieve this?

dirname $0 will get you the parent directory of the current script.

EDIT: or, more exactly, it will strip the trailing element from whatever the script was called as - /tmp/x.sh with return '/tmp', ./x.sh will return '.'.

Something like this:

$ cat test.sh
#! /bin/bash
echo $(dirname $(readlink -f $0))
$
$ ./test.sh
/home/user
$ 

Using the following works

bashPath=${0%/*}   

But the one suggested below seems more robust to me

$(dirname $(readlink -f $0))

You can combine the merits of both into something slightly more efficient than using dirname in backticks:

V=$(readlink -f "$0")
V="${V%/*}"

Can you explain to be the merits of one versus the other, and how the one you constructed combines the merits of both, if you please?

It is faster to use shell builtins than external utilities when you can, especially when processing tiny amounts of information. External utilities can run quite quickly once loaded but take time and resources to start and finish.