One of the most fundamental and powerful aspects of Git is its ability to track changes over time. This history is crucial for understanding how your project has evolved, for reverting to previous states if something goes wrong, and for collaborating effectively with others. In this section, we'll learn how to view your commit history.
The primary command for viewing your commit history is git log. When you run this command in your terminal within a Git repository, you'll see a list of commits, with the most recent commit appearing at the top. Each commit entry typically includes:
- Commit Hash: A unique identifier for the commit. This is a long string of characters, but Git often shortens it for readability.
- Author: The name and email address of the person who made the commit.
- Date: The date and time the commit was made.
- Commit Message: The descriptive message you (or someone else) wrote to explain the changes in that commit.
git logThe default output of git log can sometimes be quite verbose. Fortunately, Git offers various options to customize how you view your history. One of the most common and useful options is --oneline. This option displays each commit on a single line, showing only the abbreviated commit hash and the first line of the commit message, making it much easier to scan your history.
git log --onelineYou can also combine --oneline with other formatting options. For instance, --graph is incredibly useful for visualizing branches and merges. When used with --oneline, it draws an ASCII graph representing the branching structure, making it simple to see where branches diverged and merged back together.
git log --oneline --graphgraph TD;
A[Commit A] --> B(Commit B);
B --> C{Commit C};
C --> D[Commit D];
C --> E(Commit E - Branch);
E --> F[Commit F];
The mermaid diagram above is a simplified representation of what git log --oneline --graph might show, illustrating a linear history with a branching point. In a real scenario, the graph would show the actual commit hashes and messages.
If you want to see the changes introduced by each commit directly in the log, you can use the -p (or --patch) option. This will show the diff (the actual lines added or removed) for each commit. Be aware that this can make the output very long, especially for commits with many changes.
git log -pTo limit the number of commits displayed, you can use the -n option, followed by the number of commits you wish to see. For example, git log -n 3 will show only the three most recent commits.
git log -n 3Understanding your commit history is a cornerstone of using Git effectively. Regularly inspecting your git log output will help you grasp the evolution of your project and make more informed decisions about your development workflow.