Skip to content

Instantly share code, notes, and snippets.

@jomoespe
Last active August 16, 2019 19:10
Show Gist options
  • Save jomoespe/a5751af556335e685fbc8f2168415496 to your computer and use it in GitHub Desktop.
Save jomoespe/a5751af556335e685fbc8f2168415496 to your computer and use it in GitHub Desktop.
Fail-fast bash library example

Fail-fast the execution of a bash library script

This is an example of bash library usage. The library fail-fast if you try to use directly from CLI.

The library contains the shebang and execution permissions only for the examples. Not needed in production code (the shebaang and the permissions).

Examples

# Execute a program that uses the library
$ ./use-foo-library
Boom!

# Source the library and call some library function
$ . foo-library.sh
$ foo
Boom!
$ bar
Bang!

# Execute the library. That print error message in STDERR and finish the
# execution with code 1
$ ./foo-library.sh
foo-library.sh is a shell library, not a script!
#!/usr/bin/env bash
###############################################################################
#
# Example of fail-fast the execution of a bash library script.
#
# If you try to execute the library as a shell script, it will print an error
# message to STDERR and finish the execution with error code 1
#
###############################################################################
if [[ $(basename ${0#-}) = $(basename ${BASH_SOURCE}) ]]; then
echo "foo-library.sh is a shell library, not a script!" >& 2
exit 1
fi
foo() {
echo "Boom!"
}
bar() {
echo "Bang!"
}
#!/usr/bin/env bash
# First we "import" the library
. ./foo-library.sh
# And then we call one of the library functions
foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment