BASH functions

Published: Tuesday, 31 December 2013

hello world example

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


function hello {
  echo hello world!


This will output

hello world!

hello greeting example

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


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


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.


Linux Documentation Project - Advanced Bash-Scripting - Functions