Skip to content

Instantly share code, notes, and snippets.

@sergioro9
Last active September 8, 2024 19:45
Show Gist options
  • Save sergioro9/2bc599f5ceabd8866e23227bd0602e70 to your computer and use it in GitHub Desktop.
Save sergioro9/2bc599f5ceabd8866e23227bd0602e70 to your computer and use it in GitHub Desktop.
Bash autoload
# autoload bash scripts. Much faster than `source script.sh`
# usage: autoload script.sh
autoload() {
[ -f "$1" ] || { echo "Usage ${FUNCNAME[0]} <filename>"; return 1;}
filename="$1"
loadname="$(sed 's:\..*::' <<< $(basename $filename))"
if [ -z "$(eval echo \${${loadname}_loaded})" ]; then
functions=$(command grep -o "^[a-zA-Z0-9_:]* *()" $filename | sed 's/()//')
for f in $functions; do
eval "
$f() {
if [ \"$(eval echo \${${loadname}_loaded})\" != 2 ]; then
. $filename
eval ${loadname}_loaded=2
eval $f \$@
fi
}"
done
eval ${loadname}_loaded=1
fi
unset loadname filename
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment