Git clone with predefined user email and user name

Last Updated on by

Post summary: Small bash script to clone a Git repository and set user.email and user.name.

Usecase

There are cases when committing with a different user to a different Git repository is needed. Git offers a very easy command to change user.email and user.name, as long as you remember to do so.

git config user.name "Firstname Lastname"
git config user.email "Firstname.LastnameDoe@somemailhost.com"

I always forget to do it, so I made up a small script that I use to clone a repository and it does it for me.

Git also offers a command to globally change user.name and user.email and this is valid for each and every repository that is cloned. If the use case is to work with one name and email only, then maybe this is the best option.

git config --global user.name "Firstname Lastname"
git config --global user.email "Firstname.LastnameDoe@somemailhost.com"

Script

#!/bin/bash

if [ -z "$1" ]
then
  echo "Please provide the Git repo as argument"
  exit 1
fi

if [ -z "$2" ]
then
  echo "Please provide the user.name repo as argument"
  exit 1
fi

if [ -z "$3" ]
then
  echo "Please provide the user.email repo as argument"
  exit 1
fi

IFS='/' read -r -a urlParts <<< "$1"
urlPartsLast=${urlParts[${#urlParts[@]}-1]}

IFS="." read -r -a repoParts <<< "$urlPartsLast"
repoPartsLast=${repoParts[${#repoParts[@]}-1]}
if [ "$repoPartsLast" == "git" ]
then
  unset 'repoParts[${#repoParts[@]}-1]'
fi
repoName=$(printf ".%s" "${repoParts[@]}")
repoName=${repoName:1}

git clone "$1"

cd $repoName
git config user.name "$2"
git config user.email "$3"

The script file should be made executable with chmod +x git-clone.sh and then the script can be invoked with the following command:

./git-clone.sh https://github.com/llatinov/aws.examples.csharp.git "Firstname Lastname" Firstname.LastnameDoe@somemailhost.com

Script insights

The script checks for empty arguments and returns error in case of such. Note that user.name and user.email can be hardcoded into the script itself, this makes it easier to invoke. Then the script splits by slash (/) the Git URL into different parts. It takes the last part, which is supposed to be the repository name. The last part is additionally split by dot (.) and the git suffix is ignored. Script clones the repository and navigates to the folder where it sets the user.name and user.email.

Conclusion

This script is helping not to forget to clone a Git repository with correct user.name and user.email.

Category: Tutorials | Tags: