Snippets on the command line in bash

Posted on May 13, 2010

  1. Put your snippets into the file ~/.snips:

    { SUM=0; while read LINE; do SUM=$(($SUM+$LINE)); done; echo $SUM; }
    psql my_curren_project -U postgres
    ls /tmp #list the temp dir
    
  2. Create a file which the bash completion will call to filter the file above:

    echo 'grep "$2" ~/.snips' > ~/snip-search
    chmod u+x ~/snip-search
    
  3. Register the search script with the bash completion:

    complete -C ~/snip-search snip
    
  4. Mask the command out to execute the line from the snip file:

    alias snip=''
    

Test the completion now!

snip temp<TAB>
snip ls /tmp #list the temp dir<ENTER>

httpd                    nsmail.tmp          ssh-pvHTOq1375
keyring-Bb1Hci           orbit-jbar          zim-jbar
liferea.jbar.1742237415  plugtmp
nsmail.html              pulse-Slp1tkJgs3ui

Cool, isn't it?

P.S. There is a readline binding which will look up a command line in your complete bash history: dynamic-complete-history. A very handy feature to be sure. It is even enabled by default but they chose a very unfortunate shortcut for it - Alt+Tab.