If you working for multiple projects or companies, you may use different Github logins. If you accidentally commit something as wrong git user, it will be a pain to change the history. If you push it and add more commits on that it will be more painful to revert those changes.
If you search on google, you will see a lot of solutions. Most solutions are not straight forward, you have to spend few minutes to hours to realize the solution because of many CLI commands and copy pastings. But did you know that you can replace author name and email in the entire git history with a script?
You don’t need to use git CLI commands to change the author's name and email in the commit history. You can just run a script to replace all the commits assigned to the wrong git author.
The following illustration shows the high-level solution. Using a script, you can replace the author. This script will
- not change committed dates
- not change committed messages
Bar clone means it does not have a git working directory. It has only .git data.
git clone --bare https://github.com/user/repo.git cd repo.git
Open this script and change following OLD_EMAIL, CORRECT_NAME & CORRECT_EMAIL
#!/bin/sh git filter-branch --env-filter ' OLD_EMAIL="email@example.com" CORRECT_NAME="Your Correct Name" CORRECT_EMAIL="firstname.lastname@example.org" 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
Give executable permissions: You need permission to execute the shell script. You need to give executable permission
sudo chmod 755 script.sh
Let's run:Time to run the shell script. This script will not push those changes to your origin. So, you can review after executing.
Check author name, email, and commits messages.
git log git log --decoreate --oneline # one line log
Check twice before you run the following command.
git push --force --tags origin 'refs/heads/*'
Your git users will have to run following command to avoid that issue
git pull --allow-unrelated-histories
Also, read How to change git user for specific repo