Bash Scripting – How to Pass Parameters to Functions

bashfunctionparametersyntax

I'd like to write a function that I can call from a script with many different variables. For some reasons I'm having a lot of trouble doing this. Examples I've read always just use a global variable but that wouldn't make my code much more readable as far as I can see.

Intended usage example:

#!/bin/bash
#myscript.sh
var1=$1
var2=$2
var3=$3
var4=$4

add(){
result=$para1 + $para2
}

add $var1 $var2
add $var3 $var4
# end of the script

./myscript.sh 1 2 3 4

I tried using $1 and such in the function, but then it just takes the global one the whole script was called from. Basically what I'm looking for is something like $1, $2 and so on but in the local context of a function. Like you know, functions work in any proper language.

Best Answer

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:

#!/bin/bash

add() {
    result=$(($1 + $2))
    echo "Result is: $result"
}

add 1 2

Output

./script.sh
 Result is: 3
Related Question