19 Functions - kumar159man/MyShellLearning GitHub Wiki

Functions

Defining a function

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

What happens when we call a function before defining it

#!/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

Returning a value from a function

  • 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

Passing arguments to a function

#!/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
⚠️ **GitHub.com Fallback** ⚠️