How to pass parameters to function in a bash script?

117,760

Solution 1

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

Solution 2

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
Share:
117,760

Related videos on Youtube

user181822
Author by

user181822

Updated on September 18, 2022

Comments

  • user181822
    user181822 over 1 year

    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.

    • Wieland
      Wieland almost 8 years
      Using $1 and $2 in your example add function "works". Try echo $1 and echo $2 in it.
    • user181822
      user181822 almost 8 years
      My example was horribly incomplete, I updated it a bunch. Now afaik it won't work anymore.
    • Wieland
      Wieland almost 8 years
      Replace your result = with result=$(($1 + $2)) and add echo $result after it and it works correctly, $1 and $2 are your functions arguments.
  • user181822
    user181822 almost 8 years
    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!