🔧 What is a function?
A function is a block of code that:
- performs a specific task
- can be reused
- reduces code duplication
🔹 Function syntax
function_name () {
commands
}
OR
function function_name {
commands
}
✅ Example 1: Simple function (EXAM BASIC ⭐)
#!/bin/bash
greet () {
echo "Hello Linux"
}
greet
✅ Example 2: Function with arguments
#!/bin/bash
add () {
sum=$(( $1 + $2 ))
echo "Sum = $sum"
}
add 10 20
✅ Example 3: Function returning value (using echo)
#!/bin/bash
square () {
echo $(( $1 * $1 ))
}
result=$(square 5)
echo "Square = $result"
✅ Example 4: Function to check even or odd
#!/bin/bash
check () {
if [ $(( $1 % 2 )) -eq 0 ]; then
echo "Even number"
else
echo "Odd number"
fi
}
check 7
✅ Example 5: Function using global variable
#!/bin/bash
x=10
show () {
echo "Value of x = $x"
}
show
✅ Example 6: Function with local variable
#!/bin/bash
display () {
local msg="Linux OS"
echo $msg
}
display
✅ Example 7: Function + array
#!/bin/bash
print_array () {
echo ${arr[@]}
}
arr=(1 2 3 4)
print_array