Bash Scripting



Why Functions

DRY: Don’t Repeat Yourself

  • write once, use many times
  • reduce length of script
  • single place to edit and trouble shoot
  • easier to maintain
  • if you’re repeating yourself use a function
  • must be defined before use

How to Create a Function

Syntax:

function function_name () {
	# code
}

or

function_name () {
	# code
}

To call the function simply write the function name on a newline

do not put parantheses in the function call

eg

#!/usr/bin/bash
 
function hello(){
	echo "Hello!"
}
 
hello

functions can call other functions

eg

#1/bin/bash
 
function hello() {
	echo "Hello!"
	now
}
 
function now() {
	echo "It's $(date +$r)"
}
 
hello

functions have to defined before they are called


Positional Parameters

similar to normal

eg

#!/bin/bash
 
function hello() {
	echo "hello $1"
}
 
hello Robby
>> hello Robby

Variable Scope

  • All Variables are global by default
  • Variables have to be defined before they are used
  • if a variable is being declared in a function, it can be used globally only after the function is called

eg

#!/bin/bash
 
my_function () {
	GLOBAL_VAR=1 
}
 
# GLOBAL_VAR not available yet
echo $GLOBAL_VAR
 
# calling the function
my_function
 
# GLOBAL_VAR is available now
echo $GLOBAL_VAR
  • local variables declared using the local keyword
  • only functions can have local variables
  • it is best practice to keep variables local in functions
local LOCAL_VAR=1

Exit Statuses in Functions

functions are like shell scripts in shell scripts

  • explicitly
    • return <RETURN_CODE
  • implicitly
    • exit status is that of the last command executed in the function
  • range from 0 to 255
  • $? is exit status of last function
my_function
 
echo "$?"

eg

#!/usr/bin/bash
 
function backup_file() {
	if [ -f $1 ]
	then 
		BACK="/tmp/$(basename ${1}).$(date +%F).$$" # $$ is the PID of the script
		echo "Backing up $1 to{BACK}"
		cp $1 $BACK
	fi
}
 
backup_file /etc/hosts
 
if [ $? -eq 0 ]
then
	echo "Backup Succeeded"
fi

better version eg

#!/usr/bin/bash
function backup_file () {
	if [ -f $1 ]
	then 
		local BACK="/tmp/$(basename ${1}).$(date +%F).$$"
		echo "Backing up $1 to $BACK"
		cp $1 $BACK
	else 
		return 1
	fi
}

Practice

Exercise 1: Write a shells script that consists of a function that displays the number of files in the present working directory. Name this function “file_count” and call it in your script. If you use a variable in your function, remember to make it local.

Hint: the wc utility is used to count the number of lines, words, and bytes

Exercise 2: Modify the script from the previous exercise. Make the “file_count” function accept a directory as an argument. Next have the function display the name of the directory followed by a colon. Finally display the number of files to the screen on the next line. Call the function three times. First on /etc, then on /var, then on /usr/bin