Achieve Local Function

Bash does not support local functions, but depending on your specific script and architecture you can control the scope of your function name through subshells.

By replacing the {..} with (..) in your definition, you’ll get the output you want. The new definition of usage will be limited to the function, but so will e.g. any changes to variables:

#!/bin/bash
usage() 
{
    echo "Overall Usage"
}

function_A()
(                  # <-- Use subshell
    usage()
    {
        echo "function_A Usage"
    }

    for i in "$@"; do
        case $i in
            --help)
                usage
                shift
                ;;
            *)
                echo "flag provided but not defined: ${i%%=*}"
                echo "See '$0 --help'."
                exit 0
            ;;
        esac
    done
)

function_A --help
usage

Leave a Comment

tech