19 Functions - kumar159man/MyShellLearning GitHub Wiki
One way to define a function is shown below
#!/usr/bin/bash
#Define a function
add()
{
num1=5
num2=10
sum=$(($num1+$num2))
echo "Sum is $sum"
}
# Call the function
add
defining a function with function keyword
#!/usr/bin/bash
#Define a function
function add
{
num1=5
num2=10
sum=$(($num1+$num2))
echo "Sum is $sum"
}
# Call the function
add
#!/usr/bin/bash
# Call the function
add
#Define a function
function add
{
num1=5
num2=10
sum=$(($num1+$num2))
echo "Sum is $sum"
}
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./func1.sh ./func1.sh: line 4: add: command not found
- One way to return using echo
#!/usr/bin/bash
#Define a function
function add
{
num1=5
num2=10
sum=$(($num1+$num2))
echo $sum
}
y=$(add)
echo $y
- using return command
#!/usr/bin/bash
#Define a function
function add
{
num1=5
num2=10
sum=$(($num1+$num2))
return $sum
}
add
y=$?
echo $y
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./func1.sh 15
This method won't hold good for strings
#!/usr/bin/bash
#Define a function
function printString
{
s="Shell"
return $s
}
printString
y=$?
echo $y
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./func1.sh ./func1.sh: line 7: return: Shell: numeric argument required 2
#!/usr/bin/bash
add()
{
num1=$1
num2=$2
sum=$(($num1+$num2))
echo $sum
}
x=15
y=10
add $x $y
add 12 10
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./func2.sh 25 22