Sunday, 13 September 2009

Useful functions part1

This is the first in useful functions for shell scripts. This is useful when deploying to several servers at different versions / distributions. It allows you to check all the main programs are available to your script before it runs:

#--- START ---
cmd_check() { 
    x=0 
    for cmd in $@ 
    do 
        which ${cmd} 2>&1 > /dev/null 
        if [ $? -ne 0 ] 
        then 
            echo "${cmd} Not Found. Either install command or add path location to the PATH variable" 
            x=$(( ${x} + 1 )) 
        fi 
    done 
    if [ ${x} -ne 0 ] 
    then 
        exit ${x} 
    fi 
} 

cmd_check pax mkfifo ssh rm echo cat 
#--- END ---

http://pastie.org/614974

When running call the functions cmd_check with all the program names as arguments. If they are not available / in the PATH then the script will echo out an error and exit.

No comments: