Last active
July 7, 2024 03:30
-
-
Save chrisdothtml/36a59f6abcbf54eb4829c9caff2bda94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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