How to Pass Parameter in a Bash Function

Nilesh Katuwal Feb 02, 2024
  1. Use the Function to Print Hello World in Bash
  2. Pass String as an Argument to a Bash Function
  3. Passing Integers as Arguments to a Bash Function
How to Pass Parameter in a Bash Function

A shell function is a collection of commands that work together to form a full routine. Each function must have its own name. Shell functions have their own set of command-line options. To retrieve arguments supplied to the function, we can utilize shell variables $1, $2,… $n.

Use the Function to Print Hello World in Bash

#!/bin/bash

hello_world () {
   echo "Hello World!"
}

hello_world

Output:

Hello World!

Here, the curly braces { represent the start of the function body. The closing curly braces } define the end of the hello_world function. Finally, we are executing the function as many times as needed.

Pass String as an Argument to a Bash Function

Bash makes it extremely easy to define functions with parameters. In this example, we will create the hello_world function and pass a string as an argument by its position using shell variables. That is $1, $2, and so forth.

#!/bin/bash

hello_world () {
   echo "Hello $1"
}

hello_world "World Again!"

Here, "World Again!" will be placed on $1.

Output:

Hello World Again!

Passing Integers as Arguments to a Bash Function

In this example, we will create an add function, call it, and pass the integer as arguments. We will then pass 1 and 2 as arguments, placed in $1 and $2, respectively.

#!/bin/bash
add() {
    result=$(($1 + $2))
    echo "Result is: $result"
}
    
add 1 2

Output:

Result is: 3