Committing Changes in a Git Repository
Now that we have a basic understanding of Git commits, let's dive deeper into the process of committing changes in a Git repository.
Staging Changes
Before creating a commit, you need to stage the changes you want to include. Staging is the process of selecting the specific files or modifications you want to be part of the next commit. You can use the git add
command to stage changes:
## Stage a specific file
git add path/to/file.txt
## Stage all modified files
git add .
Creating a Commit
Once you have staged the changes, you can create a new commit using the git commit
command. When running the git commit
command, you'll be prompted to enter a commit message, which should be a concise and descriptive summary of the changes you've made.
git commit -m "Implement new feature for user authentication"
If you don't provide a commit message with the -m
option, Git will open a text editor where you can write a more detailed commit message.
Viewing Commit History
After creating commits, you can view the commit history of your repository using the git log
command. This will show you a list of all the commits, including their unique identifiers, author information, commit messages, and the changes made in each commit.
git log
You can also use the git log
command with various options to customize the output, such as limiting the number of commits displayed or showing the changes made in each commit.
## Show the last 5 commits
git log -5
## Show the changes made in each commit
git log -p
Undoing Commits
If you need to undo a commit, Git provides several options:
- Amend the Last Commit: If you want to modify the most recent commit, you can use the
git commit --amend
command. This will allow you to edit the commit message or include additional changes.
- Revert a Commit: To undo the changes introduced by a specific commit, you can use the
git revert
command. This will create a new commit that undoes the changes from the specified commit.
- Reset to a Previous Commit: If you want to discard all commits made after a specific point, you can use the
git reset
command to move the branch pointer to the desired commit.
By understanding the process of committing changes in a Git repository, you can effectively manage your project's history and collaborate with your team members.