Bash functions

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search

A bash function is nothing but subroutine a portion of code within a larger script, to performs a specific task. For example, a function called die() can be used to display an error message and exit from the script. Under bash you can simply declare and use functions in the same file. Another option is to create a library of all useful functions and include that file at the start of the script.

Creating Function

You can create a simple function called myip as follows:

myip() { lynx --dump http://www.cyberciti.biz/files/what-is-my-ip-address.php | grep 'Your IP add' | cut -d: -f2; }

Invoking myip() function

The code defined by myip() function is not executed until the function is called. myip() function can be used like normal command. To execute myip(), simply type:

myip

A Simply Script With Functions

A simple shell script using a function would look like as follows:

#!/bin/bash
# Purpose: Block ip or subnets using nginx reverse proxy server
# Written by Vivek Gite and released under GPL v2.0+
# Last updated on Dec/11/2008 by Vivek Gite (added reload support)
# -----------------------------------------------------------------
_ips=$@
_db=~/nginx/block.ips.db
_now="$(date)"
FILE=~/nginx/drop.lasso.txt
OUT=/usr/local/nginx/conf/droplasso.conf
 
# display usage message
usage(){
	echo "Usage: $0 ip1 ip2 subnet1 'ip1;spam' 'ip2;hacker' 'subnet1;spam'"
	exit 1
}
 
# add ip / subnet to database
add_ip(){
        local e="$1"
        IFS=';'
        set -- $e
        echo -e "# $_now => ${2:-unknown}\n$1" >> "$_db"
}
 
# build new database and reload the nginx web server
reload_nginx(){
        >$OUT
        egrep -v '^;' $FILE  | awk '{ print "deny " $1";"}' >>$OUT
        egrep -v '^#' $_db | awk '{ print "deny " $1";"}' >>$OUT
        /usr/local/nginx/sbin/nginx -s reload && echo 'nginx server reloaded.' || echo 'nginx server reload failed.'
}
 
# make sure we get at least one ip or subnet
[ $# -eq 0 ] && usage
 
# create $_db, if not found!
[ ! -f "$_db" ] && >$_db
 
# rebuild and reload nginx only
[ "$1" == "reload" ] && { reload_nginx; exit 0; }
 
# add all ips/subnets
for e in $*
do
        grep -q "^${e%%;*}" "$_db" || add_ip "$e"
done
 
# rebuild db and reload the webserver
reload_nginx

usage() identifies itself as a function declaration by ending in (). All function code is enclosed within { ... }. usage() is not executed until usage() is called using the following syntax:

[ $# -eq 0 ] && usage

Please consider exploring the Chapter 9: Functions for further information: