Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active July 7, 2024 03:30
Show Gist options
  • Save chrisdothtml/36a59f6abcbf54eb4829c9caff2bda94 to your computer and use it in GitHub Desktop.
Save chrisdothtml/36a59f6abcbf54eb4829c9caff2bda94 to your computer and use it in GitHub Desktop.
#!/bin/bash
###
# Usage example:
#
# . "path/to/discoverable_bash.sh"
#
# import { indent_lines } from './_utils.sh'
# call '../bins/start.sh' "foo"
###
###
# Import (source) a shell script from a relative path
# Usage: import <path>
#
# To further improve discoverability, all `import` args are ignored except
# the last one; allowing you to list your imports:
# import { some_function } from '../utils.sh'
###
function import() {
local args=($@)
local rel_path=${args[-1]}
local res=($(caller 0))
local caller_file="${res[2]}"
local caller_dir="$(dirname "$caller_file")"
local rel_caller_file="${caller_file/${PWD}\//}"
if [ ! -f "$caller_dir/$rel_path" ]; then
echo "ERROR: module '$rel_path' not found (imported from './$rel_caller_file')"
exit 1
fi
. "$caller_dir/$rel_path"
}
###
# Call a shell script from a relative path
# Usage: call <path> [...args]
###
function call() {
local rel_path=$1
local res=($(caller 0))
local caller_file="${res[2]}"
local caller_dir=$(dirname "$caller_file")
local rel_caller_file="${caller_file/${PWD}\//}"
if [ ! -f "$caller_dir/$rel_path" ]; then
echo "ERROR: file '$rel_path' not found (called from './$rel_caller_file')"
exit 1
fi
"$caller_dir/$rel_path" "${@:2}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment