Ubuntu – cd + bash completion script

bashcommand-line-interfaceUbuntu

I have web projects in /var/www/projects/some/long/path/strange-project-name

Now I want to type in terminal:

webs str{TAB}

It should autocomplete to the webs strange-project-name (basing on ls /var/www/projects/some/long/path/) and after executing the command, the pwd should point to project path. Kind of smart cd strange-project-name with autocomplete

How would you implement this feature? Some smart alias? Function in .bashrc? Script?

Some smart alias?

Best Answer

You would need a two-parter. One, a completion script:

_webs() {
    local cur prev projdir=/var/www/projects/some/long/path

    COMPREPLY=()
    cur=$(_get_cword)
    prev=${COMP_WORDS[COMP_CWORD-1]}

    COMPREPLY=( $( compgen -W '$( command ls "$projdir/$cur*" | sed "s|$projdir/||")' -- '' ) )
}
complete -F _webs webs

_get_cword depends on the bash-completions package being installed. If you don't have it then change the line:

cur=$(_get_cword)

to:

cur=${COMP_WORDS[$COMP_CWORD]}

Two, a function:

webs () {
    local projdir=/var/www/projects/some/long/path
    cd "$projdir"
    do_something_ "$@"
}