What I want trying to achieve is to create a local function within a function. At the same time, the local function will not overwrite the outer function. Below is an example of a simple function and a nested function with argument to illustrate my problem.
#!/bin/bash usage() #<------------------------------- same function name { echo "Overall Usage" } function_A() { usage() #<--------------------------- same function name { 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
Here is output.
function_A Usage function_A Usage
But what I want is
function_A Usage Overall Usage
Is is possible to achieve without change their (functions) name and order? Please?
Note: I tried the local usage()
but it seem not applicable to function.
Local functions are private methods of a type that are nested in another member. They can only be called from their containing member. Local functions can be declared in and called from: Methods, especially iterator methods and async methods.
Local functions are subroutines that are available within the same file. Local functions are the most common way to break up programmatic tasks. In a function file, which contains only function definitions, local functions can appear in the file in any order after the main function in the file.
Python | locals() function Python locals() function returns the dictionary of the current local symbol table. Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program.
local means it can only be used within the block of code where it is defined. Without the local specifier the function is global, which means it could be called from anywhere.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With