Passing Function Parameters In Bash

As a flexible and advanced scripting environment bash provides the ability to create and run functions. Functions can be created without parameters or with parameters. By using functions with parameters the functions can be used more efficiently by using different data for different cases. In this tutorial, we will examine how to pass parameters into functions in bash in different ways.

Pass Single Parameter To Bash Function

The most basic usage to pass the parameter to a function is passing a single parameter. The bash function definition does not contain parameter definition like other scripting and programming languages like Python, PHP, etc. The parameters are identified with index numbers and used with them. The first parameter in the bash function is identified with $1. In the following example, we will pass a single parameter to the function fruit(). But in order to call the function fruit(), the parenthesis is not used. The single parameter is provided after the function name inside the double quote. Even double quote is not must it is very secure to use them to prevent errors.

fruits(){
  echo $1
}

fruits "apple"

Pass Multiple Parameters To Bash Function

Multiple parameters can be passed into the bash function with the same method. We just provide multiple parameters and create $2, $3, … according to the count of the parameters. In the following example, we pass 3 parameters to the function fruits().

fruits(){
  echo $1
  echo $2
  echo $3
}

fruits "apple" "grape" "banana"
apple
grape
banana

In some cases, we may provide fewer parameters than the function requires and uses. If the function uses 3 parameters but we only provide 2 parameters the last parameter is not set and printed as empty like below.

fruits(){
  echo $1
  echo $2
  echo $3
}

fruits "apple" "grape"
apple
grape

Get Passed Parameter Count

Bash function provides some helper methods like getting the count of the passed parameters. The $# is used to return the total passed parameter count inside the function body. This information can be used to change the function execution.

fruits(){

   echo $#
}

fruits "apple" "grape"

fruits "apple"

fruits "apple" "grape" "banana"
2
1
3

List All Passed Parameters

Another useful function variable is the $@ variable which can be used to list all provided parameters to the current function. The parameters are listed in a space-separated format.

fruits(){

   echo $@
}

fruits "apple" "grape"

fruits "apple"

fruits "apple" "grape" "banana"
apple grape
apple
apple grape banana

Leave a Comment