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?
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.
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
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).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With