Modularizing Shell Scripts with Functions

Tutorial 5 of 5

1. Introduction

In this tutorial, we will dive into the principles of modularizing shell scripts with the help of functions. This technique increases the readability and maintainability of our code, leading to more efficient debugging and development.

By the end of this tutorial, you will be able to:
- Understand how to create functions in shell scripting
- Know how to call these functions within your script
- Understand how to pass arguments to functions
- Break down a larger script into smaller, manageable functions

Prerequisites:
- Basic understanding of shell scripting
- Familiarity with using a terminal/command line

2. Step-by-Step Guide

2.1 Creating Functions

In shell scripting, you create a function using the following syntax:

function_name () {
  # Commands
}

The function name should be descriptive of what the function does. Inside the brackets, you write the commands that you want the function to execute.

2.2 Calling Functions

To call a function, you simply use its name:

function_name

2.3 Passing Arguments

You can pass arguments to a function in the same way you would when running a script from the command line. Inside the function, you can access these arguments using $1, $2, and so on.

3. Code Examples

3.1 Basic Function

Let's start with a basic function that prints a greeting:

print_greeting () {
  echo "Hello, world!"
}

# calling the function
print_greeting

When you run this script, you should see the following output:

Hello, world!

3.2 Function with Arguments

Now, let's create a function that takes an argument:

print_custom_greeting () {
  echo "Hello, $1!"
}

# calling the function with an argument
print_custom_greeting "Alice"

When you run this, you should see:

Hello, Alice!

4. Summary

In this tutorial, we have learned how to create and call functions in shell scripting, and how to pass arguments to these functions. This will help you to write more structured and maintainable code.

Next, you might want to learn about function scope, return values, and more advanced function techniques. Check out these resources:

5. Practice Exercises

Now, try these exercises to test your understanding:

  1. Write a function that takes a name as an argument and prints a customized greeting.
  2. Write a function that takes two numbers as arguments and prints their sum.

Here are the solutions:

# Exercise 1
greet () {
  echo "Hello, $1!"
}

greet "Bob"

# Exercise 2
add () {
  sum=$(($1 + $2))
  echo "$1 + $2 = $sum"
}

add 3 5

Running these scripts should give you:

Hello, Bob!
3 + 5 = 8

Continue to practice creating functions for different tasks, and try to break down larger scripts into smaller functions.