How to pass parameters to function in a bash script?
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
Related videos on Youtube
user181822
Updated on September 18, 2022Comments
-
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 almost 8 yearsUsing $1 and $2 in your example add function "works". Try
echo $1
andecho $2
in it. -
user181822 almost 8 yearsMy example was horribly incomplete, I updated it a bunch. Now afaik it won't work anymore.
-
Wieland almost 8 yearsReplace your
result =
withresult=$(($1 + $2))
and addecho $result
after it and it works correctly, $1 and $2 are your functions arguments.
-
-
user181822 almost 8 yearsI 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!