Skip to content

Instantly share code, notes, and snippets.

@optisistem
Forked from sergioro9/autoload.sh
Created January 28, 2021 14:56
Show Gist options
  • Save optisistem/d1f3d036d8121164a9028aefcfca78e7 to your computer and use it in GitHub Desktop.
Save optisistem/d1f3d036d8121164a9028aefcfca78e7 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