Sunday, November 13, 2011

Import functions and variables in bash

     Those who are familiar with programming languages like C/C++/Perl/PHP etc know about importing functions and variables from other file into the program.  This enables the programmer to consolidate reusable code into a file and share it between multiple programs.

     In a similar way, bash is also capable of loading functions and variables from other programs.  It is a lot less used in bash compared to other languages, but there are a couple of places that we know off where bash uses this feature.  One of the is the /etc/profile file.

     There are three ways of doing this.  Let us assume that our functions and variables are in a file called mydefs.inc.  To include it in your code, say myscript.sh, just add one of the following to the top of myscript.sh

 . ./mydefs.inc

source ./mydefs.inc

    I prefer the second form as putting a period before the script may not be noticeable always. The filename should be present in your path if you are giving the filename without a path.  Else you should provide a rlative or absolute path. The include file is just like any other shell script, so it should have proper executable permissions set.

Now a quick example:

safeer@penguinpower:~/DEV$ cat calculator.inc
#!/bin/bash
function sumOf()
{
echo $(($1 + $2));
}


safeer@
penguinpower:~/DEV$ cat calculator.inc
#!/bin/bash:~/DEV$
cat testsum.sh
#!/bin/bash
source ${PWD}/calculator.inc
echo $(sumOf 1 2)


safeer@penguinpower:~/DEV$ ./testsum.sh
3

     I defined the function sumOf in calulator.inc file and included it in testsum.sh script at the beginning and then called the function with two arguments.  As expected the function returned the result of 1+2.