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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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
Method 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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0