Quickly Change Directory to the Repo You Just Cloned

A common pattern in my shell usage is something like this:

$ mkdir a-directory-name
$ cd !$

For those of you who aren't familiar with it, !$ is a Bash history expansion for the last argument of the previous command, so my example above creates a directory and then cd's into it. However, this trick doesn't apply when using the single argument form of git clone:

$ git clone hoelzro:linotify
$ cd !$
bash: cd: hoelzro:linotify: No such file or directory

So I augmented Bash's cd function to work in this context:

cd() {
    if [[ $1 =~ ^hoelzro: && ! -d $1 ]]; then
        cd ${1/hoelzro:/}
    elif [[ $1 =~ github:.*/ && ! -d $1 ]]; then
        cd ${1/github:*\//}
    else
        builtin cd "$@"
    fi
}

I've since converted to Zsh, so I also created a Zsh version as well:

function cd {
    local previous_command

    previous_command=$(fc -nl -1 -1)

    if [[ $previous_command =~ ^git && $previous_command =~ clone ]]; then
        if [[ ! -d $1 && $1 =~ (hoelzro|github): ]]; then
            local destination

            destination=$1
            destination=${destination#(github:*/|hoelzro:)}
            destination=${destination%[.git]}

            builtin cd "$destination"
            return
        fi
    fi
    builtin cd "$@"
}

So now when I cd !$ after a git clone, my shell enters the copy of the repository I just cloned! Both of these rely on using remote shortcuts, but since I use those almost exclusively, this works for me.

Published on 2012-12-18