BASH 101: Functions 
EXAMPLE A) Declaring a function in sum.sh script:
#!/usr/bin/bash

sum()
{
echo $1 + $2 | bc
}

# call function and pass cli
# parameters to function
sum $1 $2

Calling script:
[aesteban@localhost ~]$ ./sum.sh 1.4 1.3
2.7

EXAMPLE B) A different way to write sum.sh script:
#!/usr/bin/bash

sum()
{
RESULT=$(echo $1+$2 | bc) # or: RESULT=`echo $1+$2 | bc`
}

sum $1 $2

echo $RESULT

Calling modified script:
[aesteban@localhost ~]$ ./sum.sh 1.7 1.2
2.9

EXAMPLE C) Another way to write the same crap:
#!/usr/bin/bash

sum()
{
echo $1+$2 | bc
}

SUMRESULT=`sum $1 $2`

echo $SUMRESULT

Calling it:
[aesteban@localhost ~]$ ./sum.sh 2.9 3
5.9


[ view entry ] ( 1427 views )   |  print article

<<First <Back | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Next> Last>>



2025 By Angel Cool