0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Functions in Bash Scripts

Organize your code with functions, promoting reusability and making your scripts cleaner and easier to maintain.

What are Bash Functions?

In Bash scripting, a function is a block of code that performs a specific task. Think of it as a mini-script within your main script.

Functions help you:

  • Reuse Code: Write a piece of logic once and call it multiple times.
  • Organize Scripts: Break down complex tasks into smaller, manageable units.
  • Improve Readability: Makes your script easier to understand and maintain.

Defining a Simple Function

There are two common ways to define a function in Bash. Both achieve the same result. The most common is the first syntax.

Try running this example. It defines functions but doesn't call them yet!

#!/bin/bash

# Method 1: The most common way
my_first_func () {
  echo "Hello from my_first_func!"
}

# Method 2: Using the 'function' keyword
function my_second_func {
  echo "Hello from my_second_func!"
}

echo "Functions defined, but not called."

All lessons in this course

  1. Looping Constructs (for, while)
  2. Functions in Bash Scripts
  3. Script Arguments and Options ($@, $#, getopts)
  4. The case Statement & Pattern Matching
← Back to Linux Command Line & Bash Scripting Mastery