Bash functions

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to 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 | 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:


A Simply Script With Functions

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

# 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)
# -----------------------------------------------------------------

# display usage message
	echo "Usage: $0 ip1 ip2 subnet1 'ip1;spam' 'ip2;hacker' 'subnet1;spam'"
	exit 1

# add ip / subnet to database
        local e="$1"
        set -- $e
        echo -e "# $_now => ${2:-unknown}\n$1" >> "$_db"

# build new database and reload the nginx web server
        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 $*
        grep -q "^${e%%;*}" "$_db" || add_ip "$e"

# rebuild db and reload the webserver

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: