Shell Script · Function in Shell Scripting

Shell Scripting · Lesson 14

Function in Shell Scripting

Create reusable functions in shell scripts. Modular programming concept. Reduce duplicate code. Industry standard scripting method.

What is a Function?

A function is a reusable block of code designed to perform a specific task. Functions help reduce repetition and improve readability.

Why Use Functions?

Reusability

Write once, use many times.

Maintainability

Easier to update and debug code.

Clean Code

Improves readability and structure.

Types of Functions

  • Simple functions (no arguments)
  • Functions with arguments
  • Functions with return status
  • Functions using local variables

Function Examples

1. Basic Function Definition

A simple function that prints a message.

terminal — bash
functions
greet() {
echo "Hello from function"
}
 
greet

2. Function with Arguments

Functions can accept parameters using $1, $2, etc.

terminal — bash
functions
greet() {
echo "Hello $1"
}
 
greet "Jay"

3. Return Value from Function

Functions can return a status using return.

terminal — bash
functions
check_number() {
if [ $1 -gt 10 ]; then
return 0
else
return 1
fi
}
 
check_number 15
echo "Return status: $?"

4. Local vs Global Variables

Local variables exist only inside the function.

terminal — bash
functions
myfunc() {
local msg="Inside function"
echo $msg
}
 
myfunc
echo $msg

Best Practices

Function Best Practices

  • Use meaningful function names.
  • Keep functions small and focused.
  • Use local variables to avoid conflicts.
  • Return status codes for success/failure.

Practice Task – Functions

  • Create a function to add two numbers.
  • Create a function to check if a number is even or odd.
  • Create a function to print system info.

Next lesson: Script Arguments ($1, $2, $@)