Guide to Bash Functions (with Examples)

Bash is one of the popular scripting tools available in Unix. It stands for Bourne Again Shell. It’s a powerful tool for every Linux user or System Administrator. Let’s learn how to Bash!

Unix has 2 major categories of shells.

  • Bourne-type shell
  • C shell

Bourne shell is further classified as:

  • Korn shell (ksh)
  • Bourne shell (sh)
  • POSIX shell (sh)
  • Bourne Again shell (bash)

C shell is also further classified as:

  • C shell (csh)
  • TENEX (TOPS) C shell (tcsh)

Bash scripts are an extremely powerful and useful component for development. It can cut short repetitive tasks into a single line function call. A lot of lengthy commands can be consolidated into a single executable code.

Bash is readily available on almost all flavors of Linux and does not require any separate installation. The list of available shells can be checked by typing the following command:

cat /etc/shells

The output to this will be something as shown below:


Why Use Bash Functions?

Bash functions can:

  • Eliminate repetitive tasks
  • Save time
  • Gives a well-structured, modular and formatted sequence of activities
  • With functions, we can provide dynamic values to commands using command line arguments
  • Can simplify complex commands into a single running unit
  • Once created can be run any number of times by anyone. Build once execute many times.
  • Logical flows can be built using bash functions
  • Bash functions can be executed at server start-up or by adding a scheduled cron job
  • Commands can be debugged
  • Can have interactive shell commands

Bash is definitely a great tool to ease your workflow, and improve your project. The potential uses for it are limitless, so today we’ll only teach you the basics. Get ready to write your first script!

Getting Started with Bash

Before we start, you’ll need to SSH into your VPS server. If you’re having trouble doing that, check out this helpful tutorial.

To start with basic command options, you can check the manual pages for bash by typing:

man bash

Next we’ll have to create a .sh file. For this we’ll use the VIM Editor. To create a file use a command like this:


Now we’ll be taken to the .sh file, where we can edit it.

This will provide you a comprehensive output regarding Bash commands and its usage. Every bash script should start with the below line:


The below command displays the path of the bash script.

which bash

This will give output as shown below:


The common bash syntax is:

function functionName {
first command
second command

This can also be written as:

functionName (){
first command
second command

In a single line, this can be written as:

functionName() { first command; second command; }

Example of such a function is as shown below where we first create a directory and then change the path to point to the new directory:

sampleFunction () {
mkdir -p $1
cd $1

$1 represents the command line input argument. Bash can create dynamic inputs within the command. To verify this function, you can execute:

sampleFunction myDir

Here myDir is a valid directory name to be created. If you check the present working directory by using the pwd command you can see that you are currently within the newly created myDir.

Similarly, any commonly used command can be added as a bash function.

Remember, when you’re done using the VIM editor to edit your .sh file, you can save and exit by hitting ESC to enter command mode, and then type :wq to save and exit.

Basic Bash Functions

One of the basic examples of the bash function is as highlighted below:

   echo "My first function"

If you save this script in and execute it as ./, then you will be able to see the output as:

My first function

Echo prints the output on the console. If you swap the position of the function definition with the calling, then this will result in an error. The below snippet will give an error.

   echo "My first function"

So first you will have to define the function and then invoke it.

Bash functions can accept any number of parameters. The below example accepts two parameters:

   echo $1
   echo $2
testfunction "Hello" "World"

You can also use the interactive input and perform bash functions. One such example is as shown below:

   return $sum
read -p "Enter a number: " int1
read -p "Enter a number: " int2
add $int1 $int2
echo "The result is : " $?

In the above example, the value of addition is assigned in a variable sum, and this is returned from the function. Interactive input is taken by using read for both numbers. Finally, the result is printed using $? which stores the return value $sum from the function.

Bash functions always return one single value.

You can leave comments within the file by adding the # symbol to leave helpful notes.

Bash scripts support:

  • While loop
  • For loop
  • If statement
  • And logic
  • Or logic
  • Else If statement
  • Case Statement

Below is a short example of While loop.

while [ $isvalid ]
echo $count
if [ $count -eq 5 ];

The above example uses the while and if statements. This executes the while loop 5 times before exiting after checking the if conditional statement.

The output of this will be:


For loop can be used to increment as well as decrementing the counters. One such example of for loop is as shown below:

for (( count=10; count>0; count-- ))
echo -n "$count "

The output of this for loop will be:

10 9 8 7 6 5 4 3 2 1

In Bash && represents logical AND, while || represents logical OR.

With If statements, we can also define Else if. One such example is as shown below:

echo "Enter a valid number"
read n
if [ $n -eq 101 ];
echo "This is first number"
elif [ $n -eq 510 ];
echo " This is second number "
elif [ $n -eq 999 ];
echo " This is third number "
echo "No numbers over here"

The same above example can also be written using the case statement as shown below:

echo " Enter a valid number"
read n
case $n in
Echo " This is the first number " ;;
echo " This is the second number " ;;
echo " This is the third number " ;;
echo " No numbers over here " ;;

In case statements ;; represents case break

Final Thoughts

This completes our overview of the basic bash functions. Bash is a truly powerful tool and can be easily learned. From here you can deep dive into creating more examples and having fun exploring more potential uses of bash functions. Good luck!


The Author


Edward S. / @edvardasstabinskas

Edward is Hostinger's copywriter. He's an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward's goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Related tutorials

Leave a reply




This site uses Akismet to reduce spam. Learn how your comment data is processed.

Become a part of Hostinger now!

More in VPS
Linux Cat Command: Usage and Examples