Premium lesson

Reusing Code With Functions in Bash

Scripting·2 min read·Jan 1, 2025

In programming, a function is a reusable code structure that allows you to regroup and encapsulate multiple instructions that are part of the same logic.

It allows you to re-run these instructions multiple times from different parts of a script, without manually repeating them.

In short, you can think of a function as a mini-script within the script.

Defining functions

To define a function in Bash, you can use the following syntax:

function_name () {  instructions}

Where:

  • function_name is the name of the function.

  • instructions are the set of instructions executed by the function.

icon light bulb key

Unlock the CLI & Scripting with Bash module

Learn how to gain advanced control over the OS and automate complex routine tasks prone to manual errors with the CLI and Bash scripting.

You get immediate access to:

  • 34 focused lessons across the CLI and Bash
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module