BASH: Make “internal” functions

Under cut an example how to make pseudo-internal functions with bash-scripting having parent function life time. #!/bin/bash function testFoo() { echo "Foo OK"; # Surpize! function :testBar() { echo "Bar OK"; true || (echo "Bar 1 FAIL"; false) || return 1; false || (echo "Bar 2 FAIL"; false) || return 1; } echo Internal functions: $(compgen -A function :) :testBar; echo "Result: $?"; unset -f $(compgen -A function :) } testFoo || (echo "Foo exit"; false) || exit 1 :testBar || (echo "Bar exit"; false) || exit 1

Yep, this bash-script works.

Symbol ‘:’ is possible to use in function name, and how often have you met a function started with ‘:’? Me – never. So, lets using it!

Now about ‘internal’ function life time: before calling testFoo function testBar was not defined.
It will be defined when testFoo called.

So when we calling ‘unset -f‘ with double-dotted-functions list (compgen -A function : returns a list of defined functions with names started with ‘:’) we got a function with life time of parent function.

Ref: http://stackoverflow.com/questions/2625783/listing-defined-functions-in-bash
<EOM>

Leave a Reply

Your email address will not be published. Required fields are marked *