USD ($)
$
United States Dollar
Euro Member Countries
India Rupee

Functions and Code Reuse

Lesson 36/49 | Study Time: 15 Min

Functions in shell scripting are essential constructs that allow you to group commands into reusable blocks of code. By defining functions, you can simplify complex scripts, avoid redundancy, and improve maintainability. Functions promote modularity and clarity, making scripts easier to test, debug, and expand. 

What are Functions?

Functions are named blocks of reusable shell commands within a script. They encapsulate behavior that can be called multiple times, reducing code duplication. Functions execute only when called, improving script organization and efficiency.

Defining and Using Functions

The following are the basic ways to define and use functions in shell scripts. They show how to group commands and call them when needed.


Basic Syntax:

bash
function_name() {
commands
}


Or simply:

bash
function_name {
commands
}


Example:

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

greet "Alice"


This outputs:

text
Hello, Alice!

Passing Arguments to Functions

Arguments provided when calling functions are accessible inside the function as $1, $2, etc. $@ contains all arguments, and $# gives the count of arguments.


Example:

bash
sum() {
result=$(( $1 + $2 ))
echo "Sum is $result"
}

sum 5 10


Output:

text
Sum is 15

Returning Values from Functions

Functions return an exit status using return with a value between 0 and 255. For returning strings or numbers, use echo and command substitution.


Example:

bash
get_five() {
echo 5
}

value=$(get_five)
echo "Value returned is $value"

Advantages of Using Functions

Below are the main benefits of using functions in scripts. They promote efficient and maintainable code.


1. Code Reuse: Write once, call multiple times.

2. Modularity: Organize scripts into logical components.

3. Maintainability: Easier updates and debugging.

4. Readability: Clearer script structure.

Example: User Addition Function

bash
add_user() {
username=$1
password=$2
echo "Adding user $username"
useradd $username
echo $password | passwd --stdin $username
echo "User $username added."
}

add_user alice mypassword123
Samuel Wilson

Samuel Wilson

Product Designer
Profile

Class Sessions

1- What is Linux and Operating System Concepts 2- Linux History and Evolution 3- Linux Distributions and Their Purposes 4- Open Source Software and Licensing 5- Graphical User Interface (GUI) and Desktop Environments 6- Terminal Access and Command-Line Fundamentals 7- Getting Help and Command Documentation 8- File System Hierarchy and Directory Structure 9- Navigating Directories and Listing Contents 10- Creating, Copying, and Moving Files and Directories 11- Deleting Files and Directories 12- Symbolic and Hard Links 13- Understanding File Permissions Model 14- Modifying Permissions and Ownership 15- User and Group Management 16- Sudo and Privilege Escalation 17- Text Searching and Pattern Matching 18- Text Processing and Stream Editing 19- Compressing and Archiving Files 20- Text Editing and File Creation 21- Package Management Systems Overview 22- Installing and Updating Software with APT 23- Installing and Updating Software with YUM/DNF 24- Managing Software from Non-Repository Sources 25- Understanding Processes and Process Management 26- Viewing Running Processes 27- Process Control and Termination 28- Task Scheduling with Cron 29- Networking Concepts and IP Addressing 30- Viewing and Configuring Network Interfaces 31- Basic Network Troubleshooting 32- Shell Script Basics 33- Variables and Data Types 34- Conditional Logic in Scripts 35- Loops and Iteration 36- Functions and Code Reuse 37- Input/Output and User Interaction 38- System Authentication and Access Control 39- File System Security 40- Software Updates and Patching 41- Basic Firewall Concepts 42- System Information and Monitoring 43- Service and Daemon Management 44- System Boot Process and Runlevels 45- System Backup and Disaster Recovery 46- Comprehensive File System Management 47- System Automation Workflows 48- Multi-Concept Troubleshooting Scenarios 49- Continued Learning Pathways

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.