Languages
[Edit]
EN

Bash - how to pass arguments to function

0 points
Created by:
Teilsa
345

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

Bash

Bash - how to pass arguments to function
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join