Everything about using Git from the command line - from helpful tips and tricks to clever bash snippets.
How-Tos
Only clone a single branch
git clone <url> --branch <branch> --single-branch <folder>
Change the author of a last commit in git
git commit --amend --author "New Author Name <correct-email-address@domain.com>"
Update user email address in all commits
git filter-branch -f --env-filter '
OLD_EMAIL="liwenkz@asos.com"
CORRECT_NAME="Liwen Knight-Zhang"
CORRECT_EMAIL="development@liwen.name"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
then
git push --force --tags origin 'refs/heads/#'
Using git-log
to get repo stats
# number of releases (git tags based) in a given date range
git log --tags --since=2020-07-01 --until=2021-06-30 --simplify-by-decoration --pretty="format:%ai %d" | grep "tag: v" | wc -l
# line of code changed
git log --since=2020-07-01 --until=2021-06-30 --format= --numstat | awk '{s+=$1; s+=$2} END {print s}'
Copy all branches to a different repository
for remote in `git branch -r | grep -v master `; do git checkout --track $remote ; done
git push --all
GitHub
Using multiple GitHub accounts with ssh keys
To use two separate GitHub accounts with two different ssh keys on the same computer, you can define host aliases in ./ssh/config
to distinguish them.
Host github-lwkz
HostName github.com
User lwkz
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
Host github-nuk
HostName github.com
User news-liwenkz
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa_newsuk
Add ssh private keys to your ssh agent as usual:
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_newsuk
Test connections:
ssh -T git@github.com
ssh -T git@github-nuk
You should see something like this:
Hi lwkz! You've successfully authenticated, but GitHub does not provide shell access.
Hi news-liwenkz! You've successfully authenticated, but GitHub does not provide shell access.
Clone your repositories using aliases defined earlier:
git clone git@github.com:lwkz/repo.git
git clone git@github-nuk:news-lwkz/repo.git