Everything about using Git from the command line - from practical 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 the 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
Working with 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-spd
HostName github.com
User lwkz-spd
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa_SPD
Add SSH private keys to your SSH agent as usual:
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_SPD
Test connections:
ssh -T git@github.com
ssh -T git@github-spd
You should see something like this:
Hi lwkz! You've successfully authenticated, but GitHub does not provide shell access.
Hi lwkz-spd! 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-spd:news-lwkz/repo.git # Notice the @github-spd host
Git Worktrees
Git worktrees allow you to check out multiple branches from the same repository into separate directories. Each worktree has its own working directory with isolated files, while sharing the same Git history.