Feb 13, 2015

bash completions for my "Projects" directory

Linux bash shell has a nice feature called “completions”. You type a command and you press a TAB key. This will bring you a list of options that the command supports for completions. You type the first letter of any option and press TAB again. Now the list is reduced only to options starting from that letter. And so on.

I use terminal quite a lot. All projects for my work are located under ~/Projects/Snowflake (I work for snowflake productions gmbh). To quickly go to that projects from terminal I added the following to my ~/.bash_profile:

alias "cds=cd ~/Projects/Snowflake; cd "

Now I can just type cds projectname and get to ~/Projects/Snowflake/projectname. But I have to remember project names. Many of them are German and it is hard to remember for me. Why not use autocompletion for that? So I made a new file in /opt/local/bash_completion.d:

_cds_bash_completion()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=`ls -1 -d ~/Projects/Snowflake/*/ | cut -f6 -d'/'`
    COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
    return 0
}

complete -F _cds_bash_completion cds

This makes completions working for the cds alias that I created earlier.

The initial code for completions was taken from this tutorial.

2 comments:

  1. Hi Dmitry,

    just wondering about this. Are you aware of zsh / oh-my-zsh?
    In fact, I still use bash from time to time, but only when zsh is not available on some system. Have a look, it's great! :-)

    Greetings, Michael

    ReplyDelete
    Replies
    1. Hi :) I did not ry zsh but I certainly should :) My only problem would be that it is not used as a shell for most of clients. But I should try!

      Delete