ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Bash Shell Scripting Tutorial• 6 min read

Bash Functions & Local Scoping

Function declaration, the local keyword, and return exit codes vs stdout

Functions modularize shell scripts. By default, all variables in Bash are global unless explicitly declared with the local keyword.

Writing Clean Shell Functions

Declare functions using function_name() { ... }.

Parameters: Inside functions, $1, $2 refer to the arguments passed to the function (NOT the script arguments).

The local keyword: Always declare internal variables with local var="value" to prevent contaminating the global shell environment.

return: Returns an integer exit status (0-255). To "return" data strings, use echo and capture output via $(func).

Function with Local Variables and Return Values
#!/usr/bin/env bash

log_message() {
    local level="$1"
    local message="$2"
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")

    echo "[$timestamp] [$level] $message"
}

log_message "INFO" "Deploying microservice cluster..."
log_message "SUCCESS" "Cluster is online and healthy."
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What happens if you do NOT use the `local` keyword when declaring a variable inside a Bash function?