Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git clone and cd into it

Tags:

git

bash

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?

like image 692
Amir Shabani Avatar asked Dec 05 '25 17:12

Amir Shabani


2 Answers

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).

like image 180
NullDev Avatar answered Dec 08 '25 08:12

NullDev


I don't really like aliases with special names like cdls or gitclone because on a new system I can't remember the original commands. That's why I like the following solution for aliases:

## git extra features 
# - clone + cd 
function git() {
    if [ $1 = "clone" ]
    then 
        command git $@ && cd "$(basename "$_" .git)"
    else
        command git $@
    fi
}

Using command calls the original git command, not this one in the ~/.bashrc file (or ~/.bash_aliases file).

like image 20
Sy Ker Avatar answered Dec 08 '25 08:12

Sy Ker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!