Amend Last Commit Message in Python

This script uses subprocess to run `git commit --amend` and update the most recent commit's message in your repository.

Easy Python 3.9+ Aug 9, 2026 Git + Python 14 views 0 copies

Python code

21 lines
Python 3.9+
import subprocess
import sys


def amend_last_commit_message(new_message: str) -> None:
    """Change the message of the most recent commit."""
    result = subprocess.run(
        ["git", "commit", "--amend", "-m", new_message],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode != 0:
        print(f"Error: {result.stderr.strip()}")
        sys.exit(1)
    print(f"Amended last commit message to: '{new_message}'")


if __name__ == "__main__":
    # Example usage - replace with your desired message
    amend_last_commit_message("Fix bug in login validation")

Output

stdout
Amended last commit message to: 'Fix bug in login validation'

How it works

The script invokes git commit --amend -m via subprocess.run, which rewrites the last commit with a new message. Using capture_output=True and text=True captures stdout and stderr as strings, and check=False prevents an exception on non-zero exit so we can handle errors gracefully. On failure, it prints the error and exits with code 1; on success, it confirms the new message. This pattern is useful for scripting Git operations within Python automation.

Common mistakes

  • Forgetting to use `-m` and accidentally opening an editor.
  • Assuming the working directory is the repo root; use `cwd` parameter if needed.
  • Not checking the return code, leading to silent failures.

Variations

  1. Use `git commit --amend --no-edit` to keep the current message unchanged.
  2. Use `subprocess.check_call` and let it raise on errors.

Real-world use cases

  • Automatically fix a typo in a commit message during CI before pushing.
  • Update a commit message to include a ticket number from a script.
  • Standardize commit message format across a team via a pre-push hook.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.