DEV Community

Rob Hoelz
Rob Hoelz

Posted on

Quickly Change Directory to the Repo You Just Cloned

Originally published at hoelz.ro

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

  $ mkdir a-directory-name
  $ cd !$
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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 "$@"
}
Enter fullscreen mode Exit fullscreen mode

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!

Latest comments (2)

Collapse
 
moopet profile image
Ben Sinclair • Edited

I know it's not addressing the crux of your post, but Alt-. does the last word on the previous command.
So I do:

git clone whatever wherever
cd <alt-.>

and I am happy :)

Collapse
 
hoelzro profile image
Rob Hoelz

Yeah, Alt-. is a great alternative to !$!