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


Comments
Comments are not available for this entry.
2024 By Angel Cool