BASH functions

Published: Tuesday, 31 December 2013

hello world example

A simple function named hello that will print out “hello world!”

#!/bin/bash

function hello {
  echo hello world!
}

hello

This will output

hello world!

hello greeting example

This function takes 2 arguments - a first name and last name.

#!/bin/bash

function greet {
  echo greetings $1 and $2 family.
}

greet Joe Bloggs

This will output

greetings Joe and Bloggs family

Returning an exit code from a function

#!/bin/bash

function add_2_numbers {
  total=`expr $1 + $2`
  return $total;
}

add_2_numbers 2 5
echo answer is $?

The above will output

answer is 7

A function can only return values between 0 and 255.

Links

Linux Documentation Project - Advanced Bash-Scripting - Functions