22

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.

3
  • Using $1 and $2 in your example add function "works". Try echo $1 and echo $2 in it.
    – Wieland
    Jul 27, 2016 at 18:18
  • My example was horribly incomplete, I updated it a bunch. Now afaik it won't work anymore.
    – user181822
    Jul 27, 2016 at 18:22
  • Replace your result = with result=$(($1 + $2)) and add echo $result after it and it works correctly, $1 and $2 are your functions arguments.
    – Wieland
    Jul 27, 2016 at 18:25

2 Answers 2

28

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
1
  • 2
    I realize my mistake now. I had used $0 and $1 in the function and $0 resolved to the script name indeed. I mistook it for a parameter of the script and not the function itself. Thank you!
    – user181822
    Jul 28, 2016 at 6:57
9

In the main script $1, $2, is representing the variables as you already know. In the subscripts or functions, the $1 and $2 will represent the parameters, passed to the functions, as internal (local) variables for this subscripts.

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

add(){
  #Note the $1 and $2 variables here are not the same of the
  #main script... 
  echo "The first argument to this function is $1"
  echo "The second argument to this function is $2"
  result=$(($1+$2))
  echo $result

}

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


./myscript.sh 1 2 3 4

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .