Search code examples
bashgit

git clone and cd into it


If I wanted to make a directory and change directory into it all in one line, I could do something like this:

mkdir dir_name && cd $_

How can I do the same with git clone?

The command, git clone repo_url && cd $_, won't work obviously, because there's no such directory as repo_url. But is it possible to do it in one line?


Solution

  • If you want to find the name automatically, you could try something like this:

    git clone https://host.com/you/the-repo.git && cd "$(basename "$_" .git)"
    

    That way you don't have to specify a folder name to git.

    Explanation

    $_

    The underscore is a special bash variable that holds the last argument to the previous command.

    Example: The following command will print 'C': touch "A" "B" "C" && echo "$_"

    In the above git command, $_ will be https://host.com/you/the-repo.git

    basename

    Returns the base file name of a string parameter.

    basename string [suffix]

    The basename command reads the String parameter, deletes any prefix that ends with a / (slash) and any specified Suffix parameter, and writes the remaining base file name to standard output.

    In the above git command, the basename command will return the-repo (which is what git will have named the repo it just cloned).