The Common Series is a record of commonly used programming tools. This article is the second in the series, documenting my frequently used Git commands for easy reference. Although Git provides a GUI interface for operations, I believe there are many GUI tools for Git, but mastering the most commonly used commands is essential for a qualified programmer. After all, commands work the same everywhere, but what if one day the GUI software becomes unusable? 🐶 Moreover, the command line can execute all commands of Git.
Basic Git Operations#
The process of moving files from local to repository: Below are the commands that can push a file from your local machine to a remote repository, which I refer to as basic operations.
Installing Git#
If you want to install Git on a Mac, simply enter the command to check the git version, and it will prompt you to install it (if you haven't installed it before).
git --version
Configuring User Information#
After installing Git, configure the Git environment. These configurations only need to be set once on each computer, and of course, they can be modified later. The most common configurations in Git are setting the username and email address, where
--global
means it applies to all repositories on the system.
# Set user signature, can be viewed in the .gitconfig file
git config --global user.name <username>
# Set user email, can be viewed in the .gitconfig file
git config --global user.email <registered git repository email>
Config has three scopes: when not explicitly set, it defaults to local.
- local: valid only for a specific repository
- system: valid for all users logged into the system
Displaying Configurations#
git config --list --local
git config --list --global
git config --list --system
Obtaining a Git Repository#
There are usually two ways to obtain a repository:
- Convert a local directory into a Git repository
- Copy a repository from elsewhere to your local machine
Initializing a Repository in an Existing Directory#
git init
This command creates a .git
directory in the current directory, which includes all files necessary to initialize the repository.
Cloning a Repository#
git clone https://github.com/libgit2/libgit2
This command pulls everything from the remote GitHub libgit2 repository to your current directory.
Recording File Status#
There are 2 types of file status: tracked and untracked. Tracked means that Git can record all changes to this file (modified, deleted, renamed).
Checking File Status#
git status
# Concise output of file status: A - added to staging, M - modified files, D - deleted files, R - renamed files, ?? - untracked files
git status -s
Tracking New Files#
# After using the following command, you generally check with git status to see if the file is being tracked
git add <filename>
# Add all files to the staging area
git add . / git add -A
# Add changes of already tracked files to the staging area (does not include untracked files, i.e., new files)
git add -u
After using this command, the file will be placed in Git's staging area, and the files in the staging area are candidates to be pushed to the remote repository.
Comparing Differences#
Compare the differences between staged and unstaged files.
When we modify too many files, we may easily forget the changes made to a specific file. In this case, we can use the
diff
command to see what modifications we have made.
# The file must be in the staging area, i.e., tracked, to use this command
git diff <filename>
# If no filename is provided, it compares the differences between the working directory and the staging area
git diff
If you want to compare the files in the staging area with the files from the last commit, you can use the following command:
git diff --cached
You can also compare the differences between two different commits:
git diff <Commit id0> <Commit id1>
# To compare the differences of a specific file between two commits, add --
git diff <Commit id0> <Commit id1> -- [filename]
Renaming Files and Directories#
git mv
is the command used in Git to rename or move files or directories.
# This command moves the file from the old path to the new path and adds this change to Git's staging area
git mv <old-filename> <new-filename>
Committing Updates#
If your staging area already includes the files you want to commit, you can use the
commit
command to commit the changes to the files.
# Each commit clears the staging area
git commit -m "<Description of this commit's changes>"
Pushing Files to Remote#
Adding a Remote Repository#
If you did not clone the files from a remote repository but created the Git repository locally, you need to add the repository you want to push to before pushing to the remote repository.
git remote add https://github.com/paulboone/ticgit
Pushing#
git push origin master
This command pushes the code from the master branch to the remote origin server.
Thus, the process of creating a file and finally synchronizing it to the remote repository is successfully completed.
Next, I will document some situations encountered while using Git and the commands to use.
Commit Operations#
Modifying the Last Commit#
- Modify the information filled in the last commit
- Add modifications or files based on the last commit
Both situations can use the following command:
# This command is based on the last commit and will not generate a new commit
git commit --amend
Querying#
This section records various situations where queries are needed in the Git context.
Checking Commit History#
Entire Project's Commit History#
git log
commit ca82a6dff817ec66f44342007202690a93763949
Author: Scott Chacon <[email protected]m>
Date: Mon Mar 17 21:52:11 2008 -0700
changed the version number
commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7
Author: Scott Chacon <[email protected]m>
Date: Sat Mar 15 16:40:33 2008 -0700
removed unnecessary test
# Display all past commits in one line
git log --pretty=oneline
# Branch commit graph
git log --graph
git log --graph --pretty=oneline --abbrev-commit
# View only the last K commits
git log -n K
The output includes:
- SHA-1 checksum of each commit
- Committer's name
- Email address
- Commit date
- Commit message
File's Historical Commit Records#
View each commit record of a single file.
git log -p <filename>
# Show only the last 2 commits
git log -p -2 <filename>
Commit Records for Each Line#
Displays the last modification commit record for each line in any file.
git blame <filename>
# Limit to display specific lines
git blame -L 69,82 <filename>
Finding Bugs#
Often, when there is an issue in the current branch, but it is unclear where the problem lies, you can use the
git bisect
command to find out which commit introduced the error.
This command uses the principle of binary search:
By binary searching the range between commits that are error-free and the current problematic branch, you can find the commit that may have issues.
The git bisect start
command initiates the error search, formatted as follows:
$ git bisect start [end] [start]
End is the most recent commit, and start is an older commit. The history between them is the range of errors.
When unsure which starting commit was error-free, you can choose the very first branch.
# End is the current branch HEAD, start is the first commit 4d83cf
git bisect start HEAD 4d83cf
After executing the above command, the current code will switch to the middle commit in this range.
You can then test the current code. If there are no issues, execute the following command to mark this commit as good:
git bisect good
If there are no issues, it means the error was introduced in the latter half of the code history. Executing the above command will automatically switch Git to the midpoint of the latter half.
Then test again. If there is an issue, mark this commit as bad:
git bisect bad
At this point, it doesn't end here; there is an issue, but we need to find the first problematic commit.
Next, continue repeating this process until you successfully find the problematic commit. At this point, Git will provide the following prompt:
b47892 is the first bad commit
You can then analyze which files were committed in this commit to determine the cause of the error.
Note: You need to judge code defects yourself; Git cannot help you analyze where the problem lies.
Then, use the git bisect reset
command to exit the error search and return to the most recent code commit.
Searching for Content#
Since Git works similarly to Linux commands, it can also be used with
grep
.
git grep -n ""
Undoing Changes#
When operating Git, mistakes are inevitable. The general methods for correcting errors are either to modify them again or revert to a previous state.
Undoing File Changes#
Operations in the Working Directory#
- Revert all modifications that have not been added to the staging area.
# -- Very important; without --, it becomes the command to "switch to another branch"
git checkout -- <filename>
# Restore all files in the staging area to the working directory
git checkout .
# Restore a specific file from a commit to the staging area and working directory
git checkout [commit] [file]
- Revert modifications in the working directory relative to the staging area. If there is no corresponding file in the staging area, revert to the version pointed to by HEAD.
git restore <filename>
Operations in the Staging Area#
- Undo modifications to files in the staging area (unstage) and return them to the working directory.
git reset HEAD <filename>
# If no filename is provided, all files in the staging area will be returned to the working directory
git reset HEAD
Undoing Versions#
Commonly used after committing a version when there are conflicts in the remote that prevent merging branches. Use
git reset
to revert the version, resolve the conflicts, and then push again.
# Roll back the committed codebase to the previous version
git reset --hard HEAD^ or git reset --hard HEAD~
# Roll back two versions, and so on
git reset --hard HEAD^^:
# Roll back 100 versions
git reset --hard HEAD~100:
# Roll back to a specific version, using the first 7 digits of the version number, which can be found using git reflog
git reset --hard <version number>:
Stash Operations#
During development, it is common to have a requirement that has been developed to a certain extent, but suddenly a temporary bug needs urgent attention. In this case, the modified code can be saved in Git's stash and restored later to continue the development of the requirement after the bug is fixed.
# Save local modifications to the stash
git stash
# View the status of the stash
git stash list
# Restore the top modification from the stash without deleting the stash information
git stash apply
# Restore the top modification from the stash and delete the stash information
git stash pop
Branch Operations#
Basic Branch Operations#
# List all local branches; the current branch will be marked with an asterisk
$ git branch
# List all remote branches
$ git branch -r
# List all local and remote branches with detailed information
$ git branch -av
# Create a new branch and switch to it
$ git checkout -b [branch]
# Switch to a specified branch and update the working directory
$ git checkout [branch-name]
# Switch to the previous branch
$ git checkout -
# Delete a branch; the branch must have been merged into the upstream branch, or deletion will fail
$ git branch -d [branch-name]
# Force delete a branch, ignoring warnings
$ git branch -D [branch-name]
Merge#
Used to merge two branches.
# Merge the specified branch into the current branch
$ git merge [branch]
Rebase#
Also used for branch merging.
The operation of merging branches is basically the same as merge.
# Merge the specified branch into the current branch
git rebase [branch]
If git rebase
encounters conflicts:
- First, manually resolve the conflicts, then add the modified files to the staging area with
git add .
- After that, you do not need to
git commit
, but directly rungit rebase --continue
.
What is the difference between git merge
and git rebase
?
- After
git merge
, the merged branches will be displayed, while aftergit rebase
, there will be no record of the previously merged branches. - The order of branch merging is also different.
For detailed information, you can refer to this blog Summary of git merge and git rebase.
Cherry-pick#
Merge a specified commit into the current branch.
# Select a commit and merge it into the current branch
git cherry-pick [commit]
# Merge multiple commits into the current branch
git cherry-pick <HashA> <HashB>
# Merge a range of commits, where commit A must be earlier than commit B, and commit A will not be included in this merge
git cherry-pick A..B
# Merge a range of commits, where commit A must be earlier than commit B, and this merge will include commit A
git cherry-pick A^..B
If a conflict occurs during cherry-pick
, after manually resolving the conflict, use the --continue
command to continue the process.
- After resolving the code conflict, add the modified files back to the staging area with
git add .
- Use the following command to continue the Cherry-pick process.
git cherry-pick --continue