Functions in shell scripting are reusable blocks of code designed to perform specific tasks. They help avoid redundancy by encapsulating common operations, making scripts more modular and maintainable. Libraries, which are collections of functions, allow sharing functionality across scripts without code duplication.
Function Invocation
To call a function in a shell, use its name as you would any command. For example, a function named display_message can be executed as follows:
$ display_message
If the function requires arguments, pass them after the function name:
$ display_message "arg1" "arg2" "arg3"
Function Definition
Define a function using the syntax below:
function_name() {
# Function body
}
The function body can include commands, loops, conditionals, or calls to other functions and scripts. Here is a simple function that outputs a greeting:
greet() {
echo "Hello, World"
}
Execute this function direct in the terminal:
$ greet
Hello, World
Alternatively, store the function in a script file, such as greet.sh:
#!/bin/bash
greet() {
echo "Hello, World"
}
greet
Make the script executable and run it:
$ chmod +x greet.sh
$ ./greet.sh
Hello, World
Advanced Function Features
Beyond basic definitions, functions can handle parameters and return values for more complex operations.
Passing Arguments to Functions
Access arguments within a function using positional parameters: $1 for the first arguement, $2 for the second, and so on. Modify the greeting function to accept a custom message:
greet_user() {
echo "Hello $1"
}
Call the function with an argument:
$ greet_user "ShellUser"
Hello ShellUser
Returning Values from Functions
Use the return statement to send an exit status (integer) back to the caller. Capture this value with $? after execution:
return_value() {
return 42
}
return_value
echo "Exit status: $?"
Output:
Exit status: 42
Practical Function Examples
Here are some utility functions to enhance shell scripting workflows.
Logging Function Create a logger that prepends timestamps to messages:
log_entry() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')]: $@"
}
Usage:
$ log_entry "Operation completed successfully"
[2023-10-05 14:30:00]: Operation completed successfully
System Information Display Define a function to output OS and hardware details:
sys_details() {
echo "### Operating System Details ###"
lsb_release -a 2>/dev/null || uname -a
echo
echo "### CPU Information ###"
cpu_count=$(grep -c '^processor' /proc/cpuinfo)
cpu_model=$(grep 'model name' /proc/cpuinfo | cut -d: -f2 | head -1)
echo "CPU Count: $cpu_count"
echo "CPU Model:$cpu_model"
echo
echo "### Memory Usage ###"
mem_total=$(grep 'MemTotal' /proc/meminfo | awk '{print $2}')
mem_free=$(grep 'MemFree' /proc/meminfo | awk '{print $2}')
echo "Total Memory: ${mem_total} KB"
echo "Free Memory: ${mem_free} KB"
}
File Search Utility Search for files or directories within the current directory:
find_item() {
find . -name "$1" 2>/dev/null
}
Example usage:
$ find_item "*.txt"
./notes.txt
Digital Clock Display Implement a terminal-based digital clock:
digital_clock() {
while true; do
clear
date +'%H:%M:%S'
sleep 1
done
}
Creating and Using Libraries
Group related funcsions into a library file, such as utils.sh. Source it in the current shell environment to make functions available:
$ source utils.sh
After sourcing, call any function from the library directly.