Cloudbooklet
  • News
  • Artificial Intelligence
  • Applications
  • Linux
No Result
View All Result
Cloudbooklet
  • News
  • Artificial Intelligence
  • Applications
  • Linux
No Result
View All Result
Cloudbooklet
No Result
View All Result
Home Linux

How to Create and Use Bash Functions in Linux

by Hollie Moore
3 months ago
in Linux
Bash Function Image
ShareTweetSendShare
Readers like you help support Cloudbooklet. When you make a purchase using links on our site, we may earn an affiliate commission.

Learn how to create and use Bash functions in Linux to enhance your scripting skills. Improve code organization, efficiency, and reusability with this comprehensive guide.

ADVERTISEMENT

A Bash function is just a sequence of instructions that can be called several times. A function’s goal is to assist you make your bash scripts more understandable and to avoid repeating the same code over and over again. Bash functions are rather limited in comparison to most programming languages. In this article, we will go over the fundamentals of Bash functions and demonstrate how to use them in shell scripts in Linux.

Table of Contents

  1. Prerequisites
  2. Create File and Make it Executable
  3. How to Use Bash Functions:
  4. Bash Function Syntax
  5. Return Values
    1. Another method
  6. Variables Scope
  7. Bash Functions Arguments
  8. Conclusion 

Prerequisites

  • A Linux-powered computer.
  • Terminal and Bash shell access.
  • A text editor for writing bash scripts (Nano editor is used in the instructions).

Note: The Bash (Bourne Again SHell) is considered the default shell. If you have a different default shell, try adding the #!/bin/bash shebang at the beginning of the scripts.

Create File and Make it Executable

You can create a file using touch command.

ADVERTISEMENT
touch ~/filename.sh

Now you can make the above file executable by issuing appropriate permissions.

You might also like

Symbolic Links In Linux

Symbolic Links in Linux: What They Are and How to Use Them

2 months ago
Ubuntu Password

Reset your Forgotten Ubuntu Password in 2 Minutes

2 months ago
chmod u+x ~/filename.sh

Now your file will be executable.

You can edit the file using the nano command and add the bash functions.

ADVERTISEMENT
nano ~/filename.sh

Once you have added your functions, clickCTRL + X followed by ENTER to save and exit the file.

You can execute the file using the below command by just typing the filename.

ADVERTISEMENT
~/filename.sh

Now you can start writing your Bash functions.

How to Use Bash Functions:

Inside a shell script: The function definition should come before any calls to the function within the script in this way. Define the function with the syntax function_name() and put the necessary commands within the curly brackets {}. Use the function’s name followed by parenthesis, such as function_name, to invoke it.

ADVERTISEMENT

Directly in the terminal: Functions can also be defined at the terminal or in a bash configuration file like.bashrc or.bash_profile. To define the function, simply use the same syntax as in a shell script. Following its definition, the function can be invoked from the terminal as if it were a standard command.

Bash Function Syntax

There are two methods for declaring a bash function:

ADVERTISEMENT

The most commonly used format is:

<function name> () { 
        <commands> 
}

Alternatively, the same function can be written in a single line:

<function name> () { <commands>; }

Another option for writing a bash function is to use the reserved word function:

function <function name> {
        <commands>
}

Alternatively, the same function can be written in a single line:

function <function name> { <commands>; }

When utilizing functions, keep the following behaviors and suggestions in mind:

  1. When writing commands in one line, they must end with a semicolon (;), whether in bash scripts or directly in the terminal.
  2. By including the function reserved word, parentheses are no longer required.
  3. The commands between the curly braces { } are referred to as the function’s body. The body can contain as many declarations, variables, loops, or conditional expressions as you want.
  4. When naming functions, try to use descriptive names. Although not required for testing functions and commands, descriptive names are useful in situations when other developers will be looking at the code.

Consider the following example to better understand this:

Create a file named hello_world.sh and add the below bash function to the file. Make it executable and execute the file.

Example

#!/bin/bash

hello_world () {
   echo 'hello, world'
}

hello_world

The code defines a function called hello_world(). The function prints the string hello, world. The function is called on line 7, and the string is printed to the console.

Here is a more detailed explanation of the code:

  1. Line 3: The def keyword defines a function. The function name is hello_world. The parentheses indicate that the function takes no arguments.
  2. Line 4: The body of the function is indented. The print() statement prints the string hello, world to the console.
  3. Line 5: The closing parenthesis marks the end of the function definition.
  4. Line 7: The hello_world() function is called. The function prints the string hello, world to the console.

Return Values

Bash functions, unlike functions in “real” programming languages, do not allow you to return a value when called. When a bash function finishes, its return value is the status of the last statement run in the function, with 0 indicating success and a non-zero decimal number in the 1 – 255 range indicating failure.

The return status is provided using the return keyword and is given to the variable $?. The function is terminated using the return statement. Consider it to be the function’s exit status.

Create a new file named ~/return_values.sh and paste the below bash function.

Example

#!/bin/bash

my_function () {
  echo "some result"
  return 55
}

my_function
echo $?
output
some result
55

Another method

The simplest solution is to add the function’s output to a global variable:

#!/bin/bash

my_function () {
  func_result="some result"
}

my_function
echo $func_result
output
some result

Variables Scope

Global variables are variables that can be accessed regardless of scope from anywhere in the script. In Bash, all variables are defined as global by default, even if declared within a function. Local variables can be declared within the function body using the local keyword and utilized just within that function. Local variables with the same name can exist in many functions.

Consider the following example to see how variables scope works in Bash:

Example

#!/bin/bash

var1='A'
var2='B'

my_function () {
  local var1='C'
  var2='D'
  echo "Inside function: var1: $var1, var2: $var2"
}

echo "Before executing function: var1: $var1, var2: $var2"

my_function

echo "After executing function: var1: $var1, var2: $var2"

The script begins with the definition of two global variables, var1 and var2. Then there is a method that sets a local variable var1 and updates a global variable var2.

When a local variable with the same name as an existing global variable is set within the function body, the local variable takes priority over the global variable. Changes to global variables can be made from within the function.

output
Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D

Bash Functions Arguments

To pass any number of arguments to the bash function, place them immediately after the function’s name, separated by a space. It is best to double-quote the arguments to avoid mispairing an argument with spaces in it.

ArgumentDescription
$0The name of the function
$1The first argument passed to the function
$2The second argument passed to the function
$3 \$The third argument passed to the function \
\… \
\#
Bash Functions Arguments

As an example, consider the following:

Create a new file named ~/passing_arguments.sh and paste the below bash function.

#!/bin/bash

greeting () {
  echo "Hello $1"
}

greeting "cloudbooklet"
Hello cloudbooklet

Also read:  You might also find useful our guide on How to Use Bash wait Command in Linux

Conclusion 

In conclusion, bash functions are a powerful tool that can be used to improve the readability, maintainability, and reusability of your shell scripts. By following the steps outlined in this guide, you can easily create and use your own bash functions to automate tasks, reduce repetition, and make your scripts more efficient. Please feel free to share your thoughts and feedback in the comment section below.

Tags: CentOSDebianUbuntu
Share2Tweet1SendShare
Hollie Moore

Hollie Moore

Greetings, I am a technical writer who specializes in conveying complex topics in simple and engaging ways. I have a degree in computer science and journalism, and I have experience writing about software, data, and design. My content includes blog posts, tutorials, and documentation pages, which I always strive to make clear, concise, and useful for the reader. I am constantly learning new things and sharing my insights with others.

Leave a Reply Cancel reply

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

Related Posts

&Quot; Systemd Service On Linux

How to Create a New systemd Service on Linux: A Step-by-Step Guide

3 months ago
List Groups In Linux

How to List Groups in Linux: A Guide for Beginners

3 months ago
Hostname In Linux

How to Modify the Hostname in Linux

3 months ago
Linux Systems

Linux systems Hacked with OpenSSH Malware

3 months ago

Follow Us

Trending Articles

Chatgpt To Translate

How to Use ChatGPT to Translate Your Website or Blog

September 20, 2023

5 Best TikTok Private Account Viewer in 2023

Top 7 Free Dating Sites for Men in 2023

10 Best AI Song Generator in 2023 (Free and Paid)

How to Create and Customize Stunning Contact Poster on iPhone

Google Bard Extensions: How to Link Your Gmail, Docs, Maps, and More to an AI Chatbot

Popular Articles

Lyric Video Maker

7 Best Lyric Video Maker Software for Music Lovers

September 14, 2023

How to Create a Personal AI Assistant with LocalGPT

How to Use Adobe AI Audio Enhancer to Fix and Edit Your Recordings

HeyGen AI: Free AI Video Generator to Create Amazing Videos

Top 9 NSFW AI Story Writers to Try Today

10 Best Free Naked AI Generator: Make Realistic Naked Photos

Subscribe Now

loader

Subscribe to our mailing list to receives daily updates!

Email Address*

Name

Cloudbooklet Logo

Welcome to our technology blog, where we explore the latest advancements in the field of artificial intelligence (AI) and how they are revolutionizing cloud computing. In this blog, we dive into the powerful capabilities of cloud platforms like Google Cloud Platform (GCP), Amazon Web Services (AWS), and Microsoft Azure, and how they are accelerating the adoption and deployment of AI solutions across various industries. Join us on this exciting journey as we explore the endless possibilities of AI and cloud computing.

  • About
  • Contact
  • Disclaimer
  • Privacy Policy

Cloudbooklet © 2023 All rights reserved.

No Result
View All Result
  • News
  • Artificial Intelligence
  • Applications
  • Linux

Cloudbooklet © 2023 All rights reserved.