DEV Community

Kervie Sazon
Kervie Sazon

Posted on

Linux Fundamentals - Part 8: Bash Scripting (Functions)

Bash Function

A function is a block of code that performs a specific task.
Instead of writing the same commands over and over, you can put them inside a function and call it whenever you need.

Think of a function as a mini-program inside your script.

How to Define a Function?

The basic syntax of a Bash function looks like this:

my_function() {
  commands…
}
Enter fullscreen mode Exit fullscreen mode

The name goes first, followed by (), then the body of the function inside {}.

Example:

#!/bin/bash

hello() {
  echo "Hello from a function!"
}
Enter fullscreen mode Exit fullscreen mode

This defines a function called hello. It doesn’t do anything until you call it.

Calling (Using) a Function

To run a function, just write its name:

#!/bin/bash

hello() {
  echo "Hello from a function!"
}

hello
Enter fullscreen mode Exit fullscreen mode

If you save this as func.sh and run:

bash func.sh 

or

./func.sh
Enter fullscreen mode Exit fullscreen mode

The Output is:

Hello from a function!
Enter fullscreen mode Exit fullscreen mode

Why Use Functions?

Functions help:

  • Reuse code
  • Organize your script into smaller pieces
  • Make longer scripts easier to understand

Instead of repeating the same commands, put them inside a function and call them when needed.

Passing Arguments to Functions

Functions can get information — this is done with arguments.

Inside a function:
$1 refers to the first argument
$2 refers to the second
…and so on

Example:

#!/bin/bash

greet() {
  local name=$1
  echo "Hello, $name!"
}

greet "Kervie"
greet "Jay"
Enter fullscreen mode Exit fullscreen mode

The Ouput of this code is:

Hello, Kervie!
Hello, Jay!
Enter fullscreen mode Exit fullscreen mode

Returning Values

Unlike some languages, Bash functions don’t return values like functions in Python or Java do.

Instead, use echo to output results, and capture it like this:

#!/bin/bash

add() {
  local sum=$(($1 + $2))
  echo $sum
}

result=$(add 5 3)
echo "The total is: $result"
Enter fullscreen mode Exit fullscreen mode

Output:

The total is: 8
Enter fullscreen mode Exit fullscreen mode

This is how you get your function to “return” something useful.

Summary

Bash Function Concept How It Works
Define a function name() { … }
Call a function Just type the name
Arguments $1, $2, …
Return value Use echo and capture with $(…)

Today, I learned how to use functions in Bash to organize and reuse code inside my scripts. I discovered how to define a function, call it, and pass arguments to make it more flexible. I also learned how Bash functions handle outputs using echo instead of traditional return values.

Tomorrow, I will focus on learning Bash Arrays and understanding how they work in scripts. I also plan to practice using both functions and arrays together to strengthen what I’ve learned.

Top comments (0)