Как изменить текст коммита git после push

If a commit message contains unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub. You can also change a commit message to add missing information.

If a commit message contains unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub. You can also change a commit message to add missing information.

Rewriting the most recent commit message

You can change the most recent commit message using the git commit --amend command.

In Git, the text of the commit message is part of the commit. Changing the commit message will change the commit ID—i.e., the SHA1 checksum that names the commit. Effectively, you are creating a new commit that replaces the old one.

Commit has not been pushed online

If the commit only exists in your local repository and has not been pushed to GitHub.com, you can amend the commit message with the git commit --amend command.

  1. On the command line, navigate to the repository that contains the commit you want to amend.

  2. Type git commit --amend and press Enter.

  3. In your text editor, edit the commit message, and save the commit.

    • You can add a co-author by adding a trailer to the commit. For more information, see «Creating a commit with multiple authors.»

    • You can create commits on behalf of your organization by adding a trailer to the commit. For more information, see «Creating a commit on behalf of an organization»

The new commit and message will appear on GitHub.com the next time you push.

You can change the default text editor for Git by changing the core.editor setting. For more information, see «Basic Client Configuration» in the Git manual.

Amending older or multiple commit messages

If you have already pushed the commit to GitHub.com, you will have to force push a commit with an amended message.

We strongly discourage force pushing, since this changes the history of your repository. If you force push, people who have already cloned your repository will have to manually fix their local history. For more information, see «Recovering from upstream rebase» in the Git manual.

Changing the message of the most recently pushed commit

  1. Follow the steps above to amend the commit message.
  2. Use the push --force-with-lease command to force push over the old commit.
    $ git push --force-with-lease origin EXAMPLE-BRANCH

Changing the message of older or multiple commit messages

If you need to amend the message for multiple commits or an older commit, you can use interactive rebase, then force push to change the commit history.

  1. On the command line, navigate to the repository that contains the commit you want to amend.

  2. Use the git rebase -i HEAD~n command to display a list of the last n commits in your default text editor.

    # Displays a list of the last 3 commits on the current branch
    $ git rebase -i HEAD~3

    The list will look similar to the following:

    pick e499d89 Delete CNAME
    pick 0c39034 Better README
    pick f7fde4a Change the commit message but push the same commit.
    
    # Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
    #
    # Commands:
    # p, pick = use commit
    # r, reword = use commit, but edit the commit message
    # e, edit = use commit, but stop for amending
    # s, squash = use commit, but meld into previous commit
    # f, fixup = like "squash", but discard this commit's log message
    # x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
  3. Replace pick with reword before each commit message you want to change.

    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
  4. Save and close the commit list file.

  5. In each resulting commit file, type the new commit message, save the file, and close it.

  6. When you’re ready to push your changes to GitHub, use the push —force command to force push over the old commit.

    $ git push --force origin EXAMPLE-BRANCH

For more information on interactive rebase, see «Interactive mode» in the Git manual.

As before, amending the commit message will result in a new commit with a new ID. However, in this case, every commit that follows the amended commit will also get a new ID because each commit also contains the id of its parent.

If you have included sensitive information in a commit message, force pushing a commit with an amended commit may not remove the original commit from GitHub. The old commit will not be a part of a subsequent clone; however, it may still be cached on GitHub and accessible via the commit ID. You must contact GitHub Support with the old commit ID to have it purged from the remote repository.

Further reading

  • «Signing commits»

On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I’ll write down in detail how I did this especially for people who have no experience in Vim!

I wanted to change my five latest commits that I already pushed to the server. This is quite ‘dangerous’ because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:

Let’s say you want to change your five latest commits, and then you type this in the terminal:

git rebase -i HEAD~5

*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).

This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:

pick <commit hash> commit message

Instead of pick you need to write reword. You can do this in Vim by typing in i. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword instead of pick.

Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :. The command to save and quit is wq. So if you type in :wq you’re on the right track.

Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!

Then, if you already pushed your wrong commits, you need to git push --force to overwrite them. Remember that git push --force is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!

Now you have changed your commit messages!

(As you see, I’m not that experienced in Vim, so if I used the wrong ‘lingo’ to explain what’s happening, feel free to correct me!)

Changing the latest Git commit message

If the message to be changed is for the latest commit to the repository, then the following commands are to be executed:

  1. git commit --amend -m "New message"
    
  2. git push --force repository-name branch-name
    

Note that using --force is not recommended unless you are absolutely sure that no one else has cloned your repository after the latest commit.

A safer alternative is to use:

git push --force-with-lease repository-name branch-name

Unlike --force, which will destroy any changes someone else has pushed to the branch, --force-with-lease will abort if there was an upstream change to the repository.

Changing older commit messages

If the message needs to be amended for an older commit, then the interactive rebase tool can be used:

  1. Navigate to the repository that contains the commit you want to amend and open a terminal window.
  2. Use the git rebase -i HEAD~n command to display a list of the last nn commits in your default text editor. For example, the following command would display a list of the last three commits in your current branch:
    git rebase -i HEAD~3 
    

The list would be similiar to
this:

pick e499d89 Delete CNAME
pick 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.

# Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re- ordered; they are executed from top to
bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
  1. Replace pick with reword before each commit message that needs to be changed:
    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
    
  2. Save and close the commit list file.
  3. In each resulting commit file, type the new commit message, save the file, and close it.
  4. Force push the amended commits using git push --force.

If you are experienced with Git, then you should aware of how important to create commits for your project. If a commit message includes unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub.

In this tutorial, we are going to talk completely about how to Amend Git Commit Message easily. As it can be possible in multiple different cases, also by using various suitable Git commands so make sure to pick the one who suits your needs the most.

  • The Git Commit Amend Command
  • Commit has not been pushed online
  • How to Amend the latest Git Commit Message?
  • Amend Older or Multiple Git Commit Message using rebase
  • Amend Last Git Commit Message

You can also check Google Sheets Tips – New Google Spreadsheet Hacks, Tricks with Examples

The Git Commit Amend Command

This command will allow you to change files in your last commit or your commit message. Your old commit is replaced with a new commit that has its own ID.

The following syntax is for the amend command:

git commit --amend

Amending a commit does not simply change a commit. It substitutes it with a new commit which will have its own ID.

Commit has not been pushed online

In case the commit only exists in your local repository which has not been pushed to GitHub, you can amend the commit message with the git commit --amendcommand:

  • Navigate to the repository that includes the commit you need to amend on the command line.
  • Type git commit --amend and click on Enter
  • Later, Edit the commit message and save the commit in your text editor.
    • You can add a co-author by adding a trailer to the commit.
    • You can create commits on behalf of your organization by adding a trailer to the commit.

The new commit and message will seem on GitHub the next time you push.

Also Check: How To Undo Last Git Commit

How to Amend the latest Git Commit Message?

Are you looking for the process of amending the latest Git commit message?  This section will explain you clearly. In case the message to be amended is for the latest commit to the repository, then the following commands are to be performed:

git commit --amend -m "New message"
git push --force repository-name branch-name

Remember that using –force is not supported, as this changes the history of your repository. If you force push, people who have already cloned your repository will have to manually fix their local history.

  • How To Create Git Tags | Types of Tags in Git | Creating Git Tags with Examples
  • How To Git Stash Changes | Learn Git Stash Apply, Pop, Clear, Show, Drop
  • How To Switch Branch on Git | What is Git Switch? | Git Switch vs Checkout

Amend Older or Multiple Git Commit Message using rebase

The easiest way to amend a Git commit message is to use the “git rebase” command with the “-i” option and the SHA of the commit before the one to be amended.

You can also choose to amend a commit message based on its position compared to HEAD.

$ git rebase -i <sha_commit>

$ git rebase -i HEAD~1  (to amend the top commit)

$ git rebase -i HEAD~2  (to amend one commit before HEAD)

As an example, let’s say that you have a commit in your history that you want to amend.

The first thing you would have to do is to identify the SHA of the commit to be amended

$ git log --oneline --graph

7a9ad7f version 2 commit
98a14be Version 2 commit
53a7dcf Version 1.0 commit
0a9e448 added files
bd6903f first commit

In this case, we want to modify the message for the second commit, located right after the first commit of the repository.

Note: In Git, you don’t need to specify the complete SHA for a commit, Git is smart enough to find the commit based on a small version of it.

First, run the “git rebase” command and make sure to specify the SHA for the commit located right before the one to be amended.

In this case, this is the first commit of the repository, having an SHA of bd6903f

$ git rebase -i bd6903f

From there, you should be presented with an interactive window showing the different commits of your history.

Amend Git Commit Message using rebase rebase

As you can see, every line is prefixed with the keyword “pick”.

Identify the commit to be modified and replace the pick keyword with the “reword” keyword.

Amend Git Commit Message using rebase reword

Save the file and exit the current editor: by writing the “reword” option, a new editor will open for you to rename the commit message of the commit selected.

Write an insightful and descriptive commit message and save your changes again.

How To Amend Git Commit Message new-commit-message

Save your changes again and your Git commit message should now be amended locally.

$ git log --oneline --graph

* 0a658ea version 2 commit
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

In order for the changes to be saved on the Git repository, you have to push your changes using “git push” with the “-f” option for force.

$ git push -f 
+ 7a9ad7f...0a658ea master -> master (forced update)

That’s it! You successfully amended the message of one of your Git commits in your repository.

Amend Last Git Commit Message

If you only want to amend the last Git commit message of your repository, there is a quicker way than having to rebase your Git history.

To amend the message of your last Git commit, you can simply execute the “git commit” command with the “–amend” option. You can also add the “-m” option and specify the new commit message directly.

$ git commit --amend         (will open your default editor)

$ git commit --amend -m <message>

As an example, let’s say that you want to amend the message of your last Git commit.

$ git log --oneline --graph

* 0a658ea Last commit message
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

Execute the “git commit” command and make sure to specify the “–amend” option.

$ git commit --amend

Amend Last Git Commit Message last-commit

Amend the commit message, save and exit the editor for the changes to be applied.

Amend Last Git Commit Message amending

[master f711e51] Amending the last commit of the history.
 Date: Fri Nov 29 06:33:00 2019 -0500
 1 file changed, 1 insertion(+)


$ git log --oneline --graph

* f711e51 (HEAD -> master) Amending the last commit of the history.
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

Again, you will need to push your changes to the remote in order for other developers to get your changes. You will need to specify the “force” option as you did in the first section.

$ git push --force

+ 0a658ea...f711e51 master -> master (forced update)

That’s it!

Your Git commit message should now be amended on the remote repository.

Conclusion

In this tutorial, you learned how you can easily amend a Git commit message whether it has already been pushed or not.

You learned that you can either modify the last Git commit with the “–amend” option, or you can modify older commits with the “rebase” command.

If changes were already pushed, you will have to update them using the “git push” command and the force option.

If you are interested in Software Engineering or in Git, we have a complete section dedicated to it on the website, so make sure to check it out!

Many programmers underestimate the role of the commit message, while it is very important for managing the work. It helps other developers working on your project to understand the changes that you have made. So it must be as concrete, well-structured and clear as possible.

In this snippet, we will show you how to change your most recent commit message, as well as how to change any number of commit messages in the history.

Read on to see the options.

You can use --amend flag with the git commit command to commit again for changing the latest commit:

git commit --amend -m "New commit message"

Running this will overwrite not only your recent commit message but, also, the hash of the commit. Note, that it won’t change the date of the commit.

It will also allow you to add other changes that you forget to make using the git add command:

git add more/changed/w3docs.txt
git commit --amend -m "message"

The -m option allows writing the new message without opening the Editor.

If you want to change the message of the commit that is already pushed to the server, you should force push it using the git push command with —force flag, otherwise, your push will be rejected.

Check out Force Pushing Local Changes to Remote for more details on how to force push your changes.

In this section, we will show you the steps to follow if you want to change multiple commit messages in the history.

Let’s assume that we want to take the 10 latest commit messages, starting from the HEAD.

Run Git Rebase in Interactive Mode

Firstly, you should run the git rebase in the interactive mode:

Type «Reword»

After the first step, the editor window will show up the 10 most recent commits. It will offer you to input the command for each commit. All you need to do is typing «reword» at the beginning of each commit you want to change and save the file. After saving, a window will open for each selected commit for changing the commit message.

Type Reword

Enter a New Commit Message

After the second step, an editor will open for each commit. Type a new commit message and save the file.

Enter a new commit message

Check out Force Pushing Local Changes to Remote for more details on how to force push your changes.

It is not recommended to change a commit that is already pushed because it may cause problems for people who worked on that repository.

If you change the message of the pushed commit, you should force push it using the git push command with --force flag (suppose, the name of remote is origin, which is by default):

git commit --amend -m "New commit message."

git push --force origin HEAD

—force overwrites the remote branch on the basis of your local branch. It destroys all the pushed changes made by other developers. It refers to the changes that you don’t have in your local branch.

Here is an alternative and safer way to amend the last commit:

git push --force-with-lease origin HEAD

—force-with-lease is considered a safer option that will not overwrite the work done on the remote branch in case more commits were attached to it (for instance, by another developer). Moreover, it helps you to avoid overwriting another developer’s work by force pushing.

The git add command is used for adding changes in the working directory to the staging area. It instructs Git to add updates to a certain file in the next commit. But for recording changes the git commit command should also be run. The git add and git commitcommands are the basis of Git workflow and used for recording project versions into the history of the repository. In combination with these two commands, the git status command is also needed to check the state of the working directory and the staging area.

The git push command is used to upload the content of the local repository to the remote repository. After making changes in the local repository, you can push to share the modification with other members of the team.

Git refuses your push request if the history of the central repository does not match the local one. In this scenario, you should pull the remote branch and merge it into the local repository then push again. The --force flag matches the remote repository’s branch and the local one cleaning the upstream changes from the very last pull. Use force push when the shared commits are not right and are fixed with git commit --amend or an interactive rebase. The interactive rebase is also a safe way to clean up the commits before sharing. The git commit --amend option updates the previous commit.

Answer of @Mureinik is good but not understandable by newbie.

First method:

  1. If you only want to edit latest commit message, then you only need git commit --amend, you would see:
<your existing commit mesage foo bar> 

# Please enter the commit message fir your changes. Lines starting
# with # will be ignored, and an empty message aborts the commit.
#
# Date: Sat Aug 24 17:56:16 2019 +0800
#
# On branch is up to date with 'origin/master'.
#
# changes to be committed:
#       modified:   foo.py
#
  1. As you can see, commit message on top without any prefix of command such as pick, this is already the edit page and you can direct edit the top message and save&quit, e.g.:
<your new correction commit message> 

# Please enter the commit message for your changes. Lines starting
....
  1. Then do git push -u origin master --force or <how you push normally> --force. The key here is --force.

Second method:

  1. You can see the commit hash by git log or extract from the
    repository url, example in my case is 881129d771219cfa29e6f6c2205851a2994a8835

  2. Then you can do git rebase --interactive 881129d771219cfa29e6f6c2205851a2994a8835 or git rebase -i HEAD^ (if the latest)

  3. You would see:

pick <commit hash> <your current commit message>

# Rebase 8db7e8b..fa20af3 onto 8db7e8b
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#  d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
  1. But if you see noop then you are probably typing wrong, e.g. if you do git rebase -i 881129d771219cfa29e6f6c2205851a2994a88 which missing ^ at the end, you better quit the editor without save and figure out the reason:
noop

# Rebase 8db7e8b..fa20af3 onto 8db7e8b
...
  1. If no noop issue, then simply change the word pick to reword , other just remains (you don’t edit commit message at this point), e.g:
reword <commit hash> <your current commit message>

# Rebase 8db7e8b..fa20af3 onto 8db7e8b
#
# Commands:
#  p, pick = use commit
...
  1. Save&quit will see the edit page similar to method #1:
<your existing commit mesage foo bar> 

# Please enter the commit message fir your changes. Lines starting
# with # will be ignored, and an empty message aborts the commit.
#
# Date: Sat Aug 24 17:56:16 2019 +0800
#
# interactive rebase in progress; onto b057371
# Last command done (1 command done):
#    reword d996ffb <existing commit message foo bar>
# No commands remaining.
# You are currently editing a commit while rebasing branch 'master' on 'b057371'.
#
# changes to be committed:
#       modified:   foo.py
#
  1. Edit the message on top, same like method #1 and save&quit, e.g:
<your new correction commit message> 

# Please enter the commit message for your changes. Lines starting
....
  1. Again, same like method #1, do git push -u origin master --force or <how you push normally> --force. The key here is --force.

For more info please read the doc.

Как исправить описание только последнего коммита

Если коммит только что сделан, и он не отправлен в origin-репозитарий командой git push, то изменить описание коммита можно такой командой:

git commit —amend -m «Новое описание»

Или можно дать команду:

git commit —amend

При выполнении этой команды будет открыт текстовый редактор по-умолчанию, в котором можно будет изменить сообщение коммита. После выхода из редактора, описание коммита будет изменено. При этом будет изменена SHA-1 сумма коммита.

Кстати, исправить можно не только описание, но и файлы и их состояние в коммите. Для этого нужно просто изменить или добавить или удалить файлы в рабочей директории, зафиксировать эти изменения в индексе (командами git add или git rm и проч.), после чего можно дать команду:

git commit —amend

в результате которой GIT возьмёт текущий индекс и сделает его снимком состояния нового коммита. Опять же, при этом будет изменена SHA-1 сумма коммита.

Как исправить описание любого коммита в истории

Описанные ниже действия возможны, если коммиты еще не отправлены на удаленный репозитарий, или если программист является единственным пользователем удаленного репозитария. Описанные ниже действия являются переписыванием истории. Поэтому, если есть другие программисты, то они будут вынуждены вытянуть себе заново всю копию репозитария, чтобы у них была такая же история, что и у автора правок.

Начиная с git 1.6.6 можно использовать механизм GIT, называющийся reword. Он используется в рамках команды rebase.

Для начала находим ID коммита с неправильным комментарием. Для этого в директории с нужным git-репозиторием набираем

git log —pretty=format:»%h — %ar : %s»

На выходе получаем список коммитов с хеш-идентификаторами. Например, такой

39ba64e — 7 hours ago : redirect to order status after booking

c4d25d6 — 8 hours ago : order status

Предполагается, что надо изменить коммит c4d25d6. В дальнейших командах, контрольная сумма коммита обозначает глубину, на которую будет изменяться история.

Чтобы исправить неправильный комментарий у коммита c4d25d6, вводим следующую команду (обратите внимание на символ ^ после ID, это значит, что начинать rebase надо от его родителя. То есть, в команде rebase указывается родительский коммит того коммита, который надо отредактировать)

git rebase —interactive c4d25d6^

git откроет редактор по умолчанию, в котором вы увидите что-то типа:

pick c4d25d6 order status

pick 39ba64e redirect to order status after booking

Это сценарий действий, которые будут выполнены для изменения истории.

Меняем слово pick на слово reword, то есть нам нужно лишь изменить комментарий.

reword c4d25d6 order status

pick 39ba64e redirect to order status after booking

GIT предложит сохранить текстовый файл, что и нужно сделать. Фактически, в интерактивном режиме, это список команд для него. Он снова откроет текстовый редактор и предложит изменить комментарий для нужного коммита. После сохранения файлика git повторит весь комит, поменяет его ID и короткий хеш. Все.

Кстати, помимо reword есть еще и команда edit. После сохранения файла сценария, сценарий будет выполняться до команды edit, после чего GIT завершит работу и вернется в консоль. Будут примерно такие сообщения:

$ git rebase —interactive c4d25d6^

Stopped at c4d25d6… updated the gemspec to hopefully work better

You can amend the commit now, with

git commit —amend

Once you’re satisfied with your changes, run

git rebase —continue

В этот момент рабочая директория будет находиться в состоянии коммита c4d25d6. Можно изменить это состояние (изменить или добавить или удалить файлы), и дать команду:

git commit —amend

Откроется редактор, в котором можно будет изменить описание коммита. После закрытия редактора, отредактированный коммит будет изменен в истории. И можно дать следующую команду:

git rebase —continue

Эта команда будет дальше искать коммиты, которые нужно изменить, и будет снова останавливаться чтобы позволить внести изменения, до самого последнем коммите.

Чтобы запушить изменения, сделанные таким способом, нужно выполнить команду:

git push —force

После нее история на origin-сервере будет перезаписана. И если с репозитарием работают другие программисты, они должны будут принять всю измененную историю. Как это сделать — надо искать отдельно. Радикальный способ — это сделать git clone в отдельной директории и продолжить работу в ней. Можно пинять и отдельные изменения, но это тема для отдельной статьи.

Понравилась статья? Поделить с друзьями:
  • Как изменить текст кодом элемента
  • Как изменить текст кнопки tkinter
  • Как изменить текст кнопки swift
  • Как изменить текст клавиатуры на телефоне
  • Как изменить текст капс лок на обычный