Passing parameters to a Bash function

stivlo picture stivlo · Jun 2, 2011 · Viewed 1.1M times · Source

I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass parameters within my script. I tried:

myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

But the syntax is not correct, how to pass a parameter to my function?

Answer

dogbane picture dogbane · Jun 2, 2011

There are two typical ways of declaring a function. I prefer the second approach.

function function_name {
   command...
} 

or

function_name () {
   command...
} 

To call a function with arguments:

function_name "$arg1" "$arg2"

The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself.

Example:

function_name () {
   echo "Parameter #1 is $1"
}

Also, you need to call your function after it is declared.

#!/usr/bin/env sh

foo 1  # this will fail because foo has not been declared yet.

foo() {
    echo "Parameter #1 is $1"
}

foo 2 # this will work.

Output:

./myScript.sh: line 2: foo: command not found
Parameter #1 is 2

Reference: Advanced Bash-Scripting Guide.