Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Bash Cookbook

You're reading from   Bash Cookbook Leverage Bash scripting to automate daily tasks and improve productivity

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher Packt
ISBN-13 9781788629362
Length 264 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ganesh Sanjiv Naik Ganesh Sanjiv Naik
Author Profile Icon Ganesh Sanjiv Naik
Ganesh Sanjiv Naik
Ron Brash Ron Brash
Author Profile Icon Ron Brash
Ron Brash
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Crash Course in Bash FREE CHAPTER 2. Acting Like a Typewriter and File Explorer 3. Understanding and Gaining File System Mastery 4. Making a Script Behave Like a Daemon 5. Scripts for System Administration Tasks 6. Scripts for Power Users 7. Writing Bash to Win and Profit 8. Advanced Scripting Techniques 9. Other Books You May Enjoy

Using functions and parameters

So far in the book, we have mentioned that function is a reserved word and only used in Bash scripts that are in a single procedure, but what is a function?

To illustrate what a function is, first we need to define what a function is—a function is a self-contained section of code that performs a single task. However, a function performing a task may also execute many subtasks in order to complete its main task.

For example, you could have a function called file_creator that performs the following tasks:

  1. Check to see whether a file exists.
  2. If the file exists, truncate it. Otherwise, create a new one.
  3. Apply the correct permissions. 

A function can also be passed parameters. Parameters are like variables that can be set outside of a function and then used within the function itself. This is really useful because we can create segments of code that perform generic tasks that are reusable by other scripts or even within loops themselves. You may also have local variables that are not accessible outside of a function and for usage only within the function itself. So what does a function look like?

#!/bin/bash
function my_function() {
local PARAM_1="$1"
local PARAM_2="$2"
local PARAM_3="$3"
echo "${PARAM_1} ${PARAM_2} ${PARAM_3}"
}
my_function "a" "b" "c"

As we can see in the simple script, there is a function declared as my_function using the function reserved word. The content of the function is contained within the squiggly brackets {} and introduces three new concepts:

  • Parameters are referred to systematically like this: $1 for parameter 1, $2 for parameter 2, $3 for parameter 3, and so on
  • The local keyword refers to the fact that variables declared with this keyword remain accessible only within this function
  • We can call functions merely by name and use parameters simply by adding them, as in the preceding example

In the next section, we'll dive into a more realistic example that should drive the point home a bit more: functions are helpful everyday and make functionality from any section easily reusable where appropriate.

Using a function with parameters within a for loop

In this short example, we have a function called create_file, which is called within a loop for each file in the FILES array. The function creates a file, modifies its permissions, and then passively checks for its existence using the ls command:

#!/bin/bash
FILES=( "file1" "file2" "file3" ) # This is a global variable

function create_file() {
local FNAME="${1}" # First parameter
local PERMISSIONS="${2}" # Second parameter
touch "${FNAME}"
chmod "${PERMISSIONS}" "${FNAME}"
ls -l "${FNAME}"
}

for ELEMENT in ${FILES[@]}
do
create_file "${ELEMENT}" "a+x"
done

echo "Created all the files with a function!"
exit 0
You have been reading a chapter from
Bash Cookbook
Published in: Jul 2018
Publisher: Packt
ISBN-13: 9781788629362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime