My ~/.bashrc was getting too crowded so I wrote an autoload tool that loads functions on-demand. Suppose I want to autoload from into These are the contents of both files:

$ cat

$ cat
time::elapsed_secs() ( ... )
time::clock() ( ... )

Each of the functions in may have several lines of code which slow down initialization scripts like ~/.bashrc.

Autoloading makes initialization script faster by delaying function parsing until the function is first used.

We can see autoload in action by sourcing and using type(1) to check the contents of time::elapsed_secs:

$ .
$ type time::clock
time::elapsed_secs is a function
time::elapsed_secs () {
    if [ "" != 2 ]; then
        . /home/sergioro/.bash/;
        eval time_loaded=2;
        eval time::elapsed_secs $@;

time::elapsed_secs is ready to be evaluated upon call. In other words Bash will not parse it until it is called:

$ time::elapsed_secs "nov 30 2:23"

$ type time::elapsed_secs
time::elapsed_secs is a function
time::elapsed_secs () {
    ( echo $(($(date +'%s')-$(date -d "$*" +'%s'))) )