Jump into Docker Container Shell

This line is a nuisance:

docker exec -ti containername bash

I'm running it for every of our dozen containers many times a day. I like that it TAB-completes the container name. Other than that it's a nuisance, for these reasons:

It's slow: The variable thing about it, the container name, is not at the end, hence changing it needs to jump over or delete the command. It's not alias friendly.

It's tedious: Of course I want my bash to be interactive and connected to a pseudo-TTY. Get on with it!

A few weeks ago, I got annoyed enough to spend the 5 minutes figuring out what I like and don't like (see above). I came up with this:

Infix search of all container names:

$ dsh memcached
root@dcadb1285194:/$ exit
$ dsh mem
root@dcadb1285194:/$

A bit of error-handling:

$ dsh m
Cannot, because don't know which one to choose:
es-activemq
es-memcached

And if I don't know which one to use at all:

$ dsh
Interactive search of container names

This uses Percol for interactive search.

Here's the code:

function dsh() {
    local names=$(docker ps | awk '{ print $NF; }' | grep -v NAMES)
    if [[ $# == 0 ]]; then
            docker exec -ti $(echo "$names" | percol) bash
    else
            local selected=$(echo "$names" | grep $1)
            if (( $(echo "$selected" | wc -l) > 1 )); then
                    printf "Cannot, because don't know which one to choose: \n$(echo "$selected" | sort)\n"
            elif [[ -z "$selected" ]]; then
                    printf "Sorry, no container with '$1' found: \n$(echo "$names" | sort)\n"
            else
                    docker exec -ti $(echo "$names" | grep $1) bash
            fi
    fi
}