Thursday, November 27, 2008

Many Similar Scripts to One

Last month, I blogged about consolidating shell scripts by generalising scripts into a single script. Now I am proposing an alternative way in combining many scripts to one.

Suppose you have a dozen scripts that are scheduled to generate system information and redirect output to specific files across a number of servers. You may want to explore the use of function in shell. So each function will encapsulate individual script. If your scripts contain some common environment variables to define the PATH, output directory, and other stuffs, these common variables can now be centralised in this single script. Therefore you only have to edit this script to reflect the changes. Say you have three scripts, namely f1.sh, f2.sh and f3.sh, and they are doing similar things. You can put them like this:

$ cat all-func.sh
#! /bin/sh
#
# Consolidating all the similar functions into a single script
#


usage()
{
        echo "Usage: $0 [function|-a]"
        echo "       -a Run all the functions"
}
listfunc()
{
        for i in `egrep '^_' $0 | sed -e 's/..$//;s/^_//'`
        do
                echo $i
        done
}


globaldir="/some/global/dir"
PATH=/usr/bin:/bin:$globaldir/bin


#
# all user functions are prepend with "_" (underscore)
#
_f1()
{
        echo Running function f1 from $globaldir directory
}
_f2()
{
        echo Running function f2 from $globaldir directory
}
_f3()
{
        echo Running function f3 from $globaldir directory
}


allfunc=`listfunc`
if [ $# -eq 0 ]; then
        usage
        echo "List of functions available in this script:"
        for f in $allfunc
        do
                echo "    $f"
        done
elif [ $# -eq 1 ]; then
        case "$1" in
        -a)
                # run all the functions in this script
                for f in $allfunc
                do
                        _$f
                done
                ;;
        *)
                for f in $allfunc
                do
                        if [ "$1" = "$f" ]; then
                                _$f
                                exit 0
                        fi
                done
                echo "Error. Function \"$1\" does not exist"
                exit 1
                ;;
        esac
fi

By having all my user-defined functions prepended with "_" underscore, I can tell what are the user-defined functions wrapped in this script. Below shows the above script in action:

$ ./all-func.sh
Usage: ./all-func.sh [function|-a]
       -a Run all the functions
List of functions available in this script:
    f1
    f2
    f3

$ ./all-func.sh -a
Running function f1 from /some/global/dir directory
Running function f2 from /some/global/dir directory
Running function f3 from /some/global/dir directory

$ ./all-func.sh f2
Running function f2 from /some/global/dir directory

$ ./all-func.sh f4
Error. Function "f4" does not exist

Labels:

0 Comments:

Post a Comment

<< Home