User Tools

Site Tools


programming-languages:bash:functions

Functions

To pass arguments to a function use positional parameters $0, $1, .. where $0 always contains the bash script file name.

To return a value from the function, the echo command should be used.

#!/bin/bash
 
sum_int() {
    local x=$1
    local y=$2
    echo $(($x + $y))
}
 
sum_float() {
    local x=$1
    local y=$2
    echo $(echo $x + $y | bc)
}
 
a=2
b=3
c=2.1
d=3.2
 
int=$(sum_int $a $b)
echo "$a + $b = $int"
 
float=$(sum_float $c $d)
echo "$c + $d = $float"

The use of local variables, inside a function, allows the programmer to use variable names already defined in other functions or globally, without worry about potential name conflicts.

programming-languages/bash/functions.txt · Last modified: 2023/10/31 23:13 by tormec