Understanding Bash Functions Made Simple

The Bash shell supports functions, although they are not as powerful as their programming language cousins.  This post is designed to give you a 1 minute overview.

Syntax

function_name () { [logic]; }

or


function_name ()
{
   logic;
}

Principles

  • Functions must be defined before they can be used
    • There is no way to “declare” a function prior to use; and the Bash shell only makes one pass through a script
  • Parameters are accessed by position as positional parameters (i.e., $1, $2, … $n)
  • Functions are called like commands
  • Functions can be named like Bash variables
  • Function brackets “{” and “}” can be on separate lines
  • If the function is defined on a single line, then the last command before the close bracket “}” must have a “;” after it
  • When calling a function with parameters, use this syntax:
    • function_name param_1 param_2 param_n

Examples


#!/bin/bash
# Example of Bash function to create a log timestamp

func_timestamp ()
{
   local var_timestamp=`date +%F@%T.%N`
   echo $var_timestamp  
}

# Testing function call
echo "Start time: `func_timestamp`"
sleep 2
echo "Stop  time: `func_timestamp`"
Output:
$ ./timestamp.sh

Start time: 2015-04-06@11:08:28.494647547
Stop time: 2015-04-06@11:08:29.503555586

A more complex example involving parameter passing and dereferencing:


#!/bin/bash
# Example Bash function using parameters

# Adds two numbers
# Syntax: func_add x y result
func_add ()
{
   local x=$1
   local y=$2

   let $3=x+y
}

# Testing function call
func_add 4 8 var_result
echo Result: $var_result
Output:
$ ./add.sh

Result: 12

That’s it.

k

 

Karim Sultan
My vision is for digital innovation across the divide, by securing and simplifying the Internet and extending its reach to every citizen on Earth and beyond.

Leave a Reply

Your email address will not be published. Required fields are marked *