How to Define a Function in Bash [2 Methods]

A function in Bash is a collection of commands, necessary loops or control statements that are grouped together for a specific task. Creating a function in Bash is very simple. However, one must have a clear idea about the syntax of defining functions in bash. This article discusses two ways to define a function and provides useful insights to handle user-defined functions in the Bash shell.

2 Methods to Define Function in Bash

There are mainly two ways to define Bash functions. The main difference is whether the “function” keyword is supplied or not. To create a function in Bash, use the following syntaxes:

function_name () {compound-command} [ redirections ]

OR,

function function_name [()] {compound-command} [ redirections ]

Part of the syntaxes written within “[ ]” are optional. For instance, [ redirections ] is optional.

1. Using Parenthesis and Without “function” Keyword

The syntax of defining a Bash function without the “function” keyword includes the function name followed by parentheses and a code block enclosed in curly braces:

function_name () {
# Code block or Compound Commands
}

Look at the following example to define a function named func1 in the terminal:

func1 () {
echo "Hello from a Bash function"
}

Defining function in BashTo call the function write its name in the terminal like a Bash command:

func1

Calling a function in bashExecuting the func1 command calls the function “func1“ defined earlier. When the function is called all the commands written in the function body are executed.

A function can be declared in a single line. However, make sure the body terminates with a semicolon before the closing curly-brace like the following format:

function_name () { commands; }

For example:

func1 () { echo "Hello from a Bash function"; }

Closing semicolon for inline functionIf you look carefully when the body of “func1“ doesn’t terminate with a semicolon(;), Bash can’t recognize the end of the function.

Furthermore, if there are multiple commands in the function body, separate them by semicolon or write them one after one in a new line:

func1 () { echo "Command One"; echo "Command Two"; }

Alternatively,

func1 () { 
echo "Command One"
echo "Command Two"
}

Multiple commands separated by semicolon in Bash

EXPLANATION

Here, echo "Command one" and echo "Command two" are two commands written in the function body. These two commands need to be separated by a semicolon(;) for proper execution.

In addition, one can add redirection to redirect the output of a function to a file.

function_name () {compound-command} [ redirections ]

In this example, the multiply function writes the output to a file using “>” redirection symbol:

multiply () {
result=$(($1 * $2))
echo "The result of multiplication: $result"
} > output.txt

# Call the function
multiply "50" "2"
EXPLANATION

> output.txt after the closing curly brace indicates that the output of the function is redirected to the output.txt file. The function takes two arguments that are provided after the function name while calling the function. The function utilizes the arguments by the positional parameters $1 and $2. Within the function, it multiplies the arguments and prints the result in the output.txt file.

Redirecting output of a Bash functionCalling the function with arguments "50" and "2" doesn’t show anything in the terminal. However, if you look at the content of the output.txt file using cat output.txt, you can see the result of multiplication is written in that file.

Another important thing to note, the body of the function should be separated from the brace by a space or newline. Because “{” is a reserved symbol for brace expansion. Any character just after the opening curly brace of a function may lead to an unexpected brace expansion. Try to define the following function that doesn’t have space between the opening curly brace and the body of the function:

func () {echo "This is a Bash function"; }

Spacing after opening curly brace of a Bash functionAs you see it raises a syntax error near the opening curly brace of the function body.

2. Using the “function” Keyword

The function keyword is reserved in Bash to define functions. Put the word “function” before the function name to create a Bash function like below:

function function_name() {
# Code block or Compound Commands
}

The following Bash script contains a function funckey that is declared using the reserved word “function”:

#!/bin/bash

# Function definition
function funckey () {
echo "Hello from a Bash function"
}

# Call the function
funckey

Defining function using function keywordOnce you run the script, it calls the function “funckey“ and prints the message “Hello from a Bash function”. This message is written within the function using the echo command.

When the word “function” is supplied to define a function, the parenthesis “()” after the function name becomes optional. Then the syntax of a function can be written as:

function function_name {
# Code block or Compound Commands
}

The following script defines the function funckey1 without having parenthesis in its definition:

#!/bin/bash

# Function definition
function funckey1 {
echo "This function doesn’t have parenthesis in its definition."
}

# Call the function
funckey1

Defining function without braces after function nameOnce executed the function defined within the script works perfectly though it lacks the parentheses after the function name.

Moreover, one can define a Bash function in the terminal using the “function” keyword in a compact form:

function function_name { commands; }

For example:

function func {  echo "This function is defined in a single line"; }

Single line command defined in terminal using function keywordThe func function is defined using the “function” keyword in a single line in the terminal.

Valid Function Name in Bash

When naming a Bash function, choose a valid shell name that clearly represents its purpose. Ensure that the function name does not conflict with special Bash built-ins. To retrieve the function name within the function itself, use the FUNCNAME variable:

my_function() {
echo "The name of the function is: $FUNCNAME"
}

Getting function name using FUNCNAME variableHere, FUNCNAME retrieves the function name “my_function“.

In default mode, a function name can be any unquoted shell word that does not contain “$”. Even an underscore can be a valid function name. Look at the following function where an underscore is used as a function name:

_(){
echo "$FUNCNAME is a valid function name."
}

Underscore as function name in BashCalling the function using the name underscore(_) works fine.

In fact, a single colon is also a valid function name:

: (){
echo "Another weird function name"
}

Colon as function name in BashHere, the function : is defined and called in the terminal.

Make a Function Permanent to Shell Sessions

A function defined in the terminal goes away when the session ends. To make a function permanent to shell sessions write it in the bashrc file. Follow the steps below to easily add a function in the bashrc file permanently:

  1. Open the ~/.bashrc file in any text editor. To open it in the built-in nano editor use the code below:
    sudo nano ~/.bashrc

    Making functions Permanent to shell sessionsAlternatively, if your sudo permission doesn’t expire in the current shell session, you can use:

    nano ~/.bashrc
  2. Now, go to the end of the file. Write the function that you want to make permanent. For instance, the following “func1“ function is added at the end of the ~/.bashrc file.
    func1 () {
    echo "Hello from a Bash function"
    }

    Adding functions in the bashrc file

  3. Save and close the file. For nano, it’s CTRL+O and then CTRL+X.
  4. For the changes to take effect, close the terminal. Now simply open the terminal and write the newly added function name in the terminal. This will execute the function irrespective of shell sessions.

    Calling a permanent functionAs expected, “func1“ executes the function added in the ~/.bashrc file.

A lengthy function can make the bashrc file messy. Moreover, if there are multiple functions to add then better to put them all together in a separate file. Then source that separate file in the ~/.bashrc file. For instance, consider a file “additional_functions“ containing some user-defined functions such as welcome and multiply. Check its content using the command below:

cat additional_functions

Storing user defined functions in a separate fileTo source that file in the ~/.bashrc file, run the following script:

#!/bin/bash

path=./additional_functions
if [[ -f "$path" ]]; then
source "$path"
fi
EXPLANATION

The script checks if a file named “additional_functions” exists in the current directory. If the file exists, it sources (includes) the content of that file into the current script using the source command.

Sourcing function in the bashrc fileNow, “welcome“ and “multiply“ functions can be called from the terminal. They seem to be added in the bashrc file even though they aren’t. They will be available in a different shell session only after executing the script.

Before using the script change the path variable. Replace path with the actual path to the script containing your functions.

NOTE: Replacing source with dot(.) also works. Dot(.) is just equivalent to the source command.

How to Get a List of Functions

To get a list of the functions defined in the system use the declare command. The -F option is useful for this purpose:

declare -F

Listing bash functionsThe output shows a long list of functions. It also contains user-defined functions that are added in the bashrc file.

Moreover, -f option of the declare command shows the content of functions as well:

decare -f

Visualizing the content of a Bash functionRun the command and scroll down the output. It shows a lot of functions along with the content of a function welcome that was recently added in the bashrc file.

To print a particular function’s contents, write the name of that function after the -f option like the following:

declare -f welcome

Visualizing the content of a particular Bash functionThe output shows the content of the “welcome“ function only.

Conclusion

To sum up, defining functions in Bash is super easy. Nonetheless, one needs to get used to the syntax. Also, Bash offers options to list down all the functions and their contents. I hope this article has helped you understand the syntax and various ways to create functions in Bash.

People Also Ask

How to delete a Bash function?

To delete a function use the unset command with the -f option. The syntax is unset -f function_name. However, the -f option is not mandatory. It just indicates that you are unsetting a function.

Can I put a variable as a function name in Bash?

No. In the traditional sense, you can’t directly use a variable as a function name. Also, it’s not suggested. But if you deliberately want to use a variable as a function name, you can achieve that using associative arrays.

What are the rules for function names in Bash?

There is absolutely no fixed rule for function names in Bash. A single letter, number and even underscore or a colon can be the name of a Bash function. The only thing to keep in mind is that function names should be a valid shell word.

How to define a Bash function that can be used in any script?

To define a Bash function that can be used in any script write the function in the ~/.bashrc file. However, this can make the bashrc file flooded with user-defined functions. Putting the functions in a separate file and source them in the bashrc file is a better choice.

How Bash functions are different from aliases?

The main difference between aliases and functions is- aliases don’t take arguments but Bash functions do. If you write an alias like l='ls -l' then there is no option to provide an argument in that alias. On the other hand, a Bash function can take arguments by utilizing positional parameters. Moreover, an alias can be bypassed by the escape character backslash. For instance, the alias l can be escaped by '\l'. Furthermore, alias precedes Bash functions. It means Bash executes the alias if an alias and a function are defined under the same name.

Related Articles


<< Go Back to Bash Functions | Bash Scripting Tutorial

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment