How to define and call functions on Bash Script on Ubuntu 22.04

To Define And Call Functions On Bash Script On Ubuntu 22.04

Introduction

A shell function is similar to a function in C: It is a sequence of commands that do a single job. Typically, a function is used for an operation that you tend to do frequently in a shell script. Before you can call a function in a shell script, you must define it in the script.

Procedure Steps:

Step 1: Check the OS version by using the below command

root@linuxhelp:~# lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 22.04.3 LTS
Release:	22.04
Codename:	jammy

Step 2: Create a file by using vim editor

root@linuxhelp:~# vim function.sh
Add the following lines in that file
#!/bin/bash
simple_function()
{
        echo "This is the simple function"
}
simple_function

Step 3: Give execute permission to the file by using the below command

root@linuxhelp:~# chmod +x function.sh 

Step 4: Now run the script with prefix ./ by using the below command

root@linuxhelp:~# ./function.sh 
output :
This is the simple function

Step 5: Create an another file by using vi editor

root@linuxhelp:~# vim install_function.sh
Add the following lines in that file
#!/bin/bash
ret=`systemctl status $1 &> /root/output ; echo $?`
install_function()
{
        echo "Installing $1 service"
}
exit_function()
{
        echo "Service Already exist"
}
if [[ "$ret" = "0" ]]
then
        exit_function
else
        install_function
fi

Step 6: Give execute permission to the file by using the below command

root@linuxhelp:~# chmod +x install_function.sh 

Step 7: Now run the script with not installed service as argument by using the below command

root@linuxhelp:~# ./install_function.sh apache2
Output :
Installing  service

Step 8: Now again run the script with already installed service as argument by using the below command

root@linuxhelp:~# ./install_function.sh ssh
Output : 
Service Already exist

Conclusion:

We have reached the end of this article. In this guide, we have walked you through the steps required to define and call functions on Bash Script on Ubuntu 22.04. Your feedback is much welcome.

FAQ
Q
How to pass a function in a Shell Script?
A
To invoke a function, simply use the function name as a command before that need to define a function.
Q
What is Shell Scripting Syntax?
A
A shell script is a text file that contains a sequence of commands for a UNIX-based operating system.
Q
How to give execute permission to the file on Linux?
A
By using the following command you can give execute permission to the file
# chmod +x
Q
What is the syntax of the function?
A
Syntax :
functionName ()
{
Commands to be executed
}
Q
What is the use of function in Shell Script?
A
A function is used for an operation that you tend to do frequently in a shell script.