Linux Shell Scripting Tutorial – Module 5: Functions in Bash

Linux Shell Scripting Tutorial – Module 5: Functions in Bash

AI Reading

Quick summary of this article

This module teaches how to use functions in Bash scripts. Functions are reusable blocks of code that group commands, making scripts cleaner and easier to manage. You can pass arguments to functions, return values, use local variables, and even nest functions inside each other. The module also includes practical assignments to practice these concepts.

  • Functions are defined using function_name() { commands } or function function_name { commands }, and called by simply typing their name.
  • Arguments are passed to functions using $1, $2, etc., with $# for the count and $@ for all arguments.
  • To return actual values from a function, use echo combined with command substitution, like sum=$(add_numbers 5 10).
  • The local keyword inside a function prevents variables from overwriting global ones, keeping scripts safer.
  • Functions can call other functions (nested functions), making scripts modular and easier to build complex logic.

Module 5: Functions in Bash

Functions are reusable blocks of code that group commands together.
Instead of rewriting the same code multiple times, you can put it inside a function
and call it whenever needed. Functions improve script structure and reduce errors.

✅ Defining a Function

Basic syntax:


function_name () {
  commands
}
# OR
function function_name {
  commands
}
  

✅ Example: Simple Function


#!/bin/bash
hello_world() {
  echo "Hello, World from function!"
}

# Call the function
hello_world
  

Output:


Hello, World from function!
  

✅ Functions with Arguments

  • $1, $2, … → Function parameters
  • $# → Number of arguments
  • $@ → All arguments

#!/bin/bash
greet() {
  echo "Hello, $1! Welcome to $2."
}

greet "Alice" "Linux Scripting"
  

Output:


Hello, Alice! Welcome to Linux Scripting.
  

✅ Returning Values

Functions can return status codes (0 for success, non-zero for error).
For actual values, use echo and command substitution.


#!/bin/bash
add_numbers() {
  result=$(( $1 + $2 ))
  echo $result
}

sum=$(add_numbers 5 10)
echo "Sum is: $sum"
  

Output:


Sum is: 15
  

✅ Local Variables

Use local inside a function to avoid overwriting global variables.


#!/bin/bash
my_func() {
  local msg="Hello"
  echo $msg
}

msg="Hi"
my_func
echo $msg
  

Output:


Hello
Hi
  

✅ Nested Functions


#!/bin/bash
outer() {
  echo "Outer function"
  inner
}

inner() {
  echo "Inner function"
}

outer
  

✅ Summary

  • Functions group reusable code into blocks.
  • Arguments are passed using $1, $2, etc.
  • Use echo with command substitution to return values.
  • Use local for variables inside functions.
  • Functions can call other functions, making scripts modular.

✅ By the end of this module, you can create, use, and manage functions in Bash,
making your scripts cleaner and more powerful.

Module 5: Bash Function Assignments

These assignments will help you practice using functions, arguments, local variables, and nested functions in Bash. Try solving them practically to reinforce your learning.

 

✅ Assignment 1: Greeting Multiple Users

Write a function that greets multiple users by reading names from command-line arguments. Use $@ to process all arguments and print a greeting for each user.

Example Output:


Hello, Alice!
Hello, Bob!
Hello, Charlie!

✅ Assignment 2: Calculator Function

Write a function calculator that takes three arguments: two numbers and an operator (+, -, *, /) and returns the result using echo. Use command substitution to capture the result.

Example Call:


result=$(calculator 10 + 5)
echo "Result: $result"

Expected Output:


Result: 15

✅ Assignment 3: Check File Type

Write a function check_file that takes a filename as an argument and prints whether it is a regular file, directory, or something else using conditional statements.

Example Call:


check_file myfile.txt

Expected Output:


myfile.txt is a regular file

✅ Assignment 4: Library Book Tracker

Write a simple library system using functions:

  • add_book: Adds a book to a file books.txt
  • list_books: Lists all books in books.txt
  • search_book: Searches for a book by name

Example:


add_book "The Alchemist"
add_book "Linux Essentials"
list_books
search_book "Alchemist"

Expected Output:


Books in library:
1. The Alchemist
2. Linux Essentials

Book found: The Alchemist

✅ Assignment 5: Factorial Calculator

Write a recursive function factorial that calculates the factorial of a number. Use nested function calls and return the result using echo.

Example Call:


result=$(factorial 5)
echo "Factorial of 5 is $result"

Expected Output:


Factorial of 5 is 120

Leave a Reply

Your email address will not be published. Required fields are marked *