EN
Bash - how to pass arguments to function
0
points
This article will show you how to pass arguments to function in Bash.
Quick solution:
#!/bin/bash
my_function(){
# here we can refer to subsequent arguments using $1, $2 and $3
}
# number of argument
# 1 2 3
my_function "one" "two" "three"
Practical examples
A function that displays the argument given to it:
#!/bin/bash
print_parameter(){
echo $1
}
print_parameter "Dirask"
print_parameter "wiki for code"
Output:
Dirask
wiki for code
A function that adds two numbers given as its parameters:
#!/bin/bash
add_numbers(){
echo $(($1 + $2))
}
add_numbers 1 2
add_numbers 10 13
Output:
3
23