Lazy initialization in bash profile

Unrelated but beautiful photo by Ryan McGuire

Sometimes your ~/.profile is too heavy for comfortable use — it is executed every time you create a new terminal tab or window, open new PhpStorm terminal console, etc. For example if you install nvm via git (as “Git install” section describes), the following couple of lines can take considerable time to execute (1–1.5 seconds for my laptop):

How one can avoid that slowness? Make a “lazy alias”! Here is the technique:

How it works:

  1. Initially nvm is bound to a custom bash function, and this happens without any delays.
  2. When user executes nvm --with --some=options, alias executes that function (and passes all parameters along, of course).
  3. The function removes alias, executes slow code, and finally executes nvm with original parameters.
  4. Next time user executes nvm it will be real executable (or command, or whatever happens in $NVM_DIR/

Of course, this trick should work with any 3rd party command that has some slow setup or initialization stage.

Hope this helps someone get more productive!