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.
Python code
21 linesimport 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
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
- Use `git commit --amend --no-edit` to keep the current message unchanged.
- 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
More from Git + Python
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
- Detect Merge Conflict Markers in a File with Python easy
Keep learning
Related tutorials and quizzes for this topic.