Git Commit
One of the fundamental commands in Git is
git commit
, which allows developers to save their changes with a descriptive
message. .
1. Basic Commit:
The most straightforward use of git commit
involves saving changes to the
repository. After staging the changes using git add
, execute the commit
command:
bashgit add .
git commit -m "Initial commit"
This creates a new commit with the specified message, marking a snapshot of the project at that point in time.
2. Amending the Last Commit:
To include changes you forgot or need to correct in the last commit, use the
--amend
option:
bashgit add forgotten_file.txt
git commit --amend -m "Improved description"
This command combines the staged changes with the previous commit and updates the commit message.
3. Interactive Staging:
The -p
or --patch
option allows you to interactively stage changes.
Git prompts you for each change, giving you the option to stage, skip, or split the changes:
bashgit add -p
This feature is useful when you want to review and commit only specific parts of your modifications.
4. Committing All Changes, Including Untracked Files:
By using the -a
or --all
option with git commit
, you
can commit all changes, including modifications, deletions, and untracked files:
bashgit commit -am "Add new feature"
This is a convenient way to quickly commit all changes without explicitly using
git add
.
5. Committing with Date
You can set the commit date explicitly using the --date
option. This is
particularly useful when you need to backdate a commit or set a specific date for historical
reasons:
bashgit commit --date="YYYY-MM-DD HH:MM:SS" -m "Commit with a custom date"
6. Committing Only Staged Changes:
To commit only the changes that are already staged, excluding any unstaged modifications, use
the --only
option:
bashgit commit --only -m "Committing only staged changes"
7. Signing Commits:
For added security and traceability, you can sign your commits with a GPG key. Use the
-S
or --gpg-sign
option:
bashgit commit -S -m "Signed commit"
This helps verify the authenticity of your commits.