How to Use Git?
What is Git
Git is a distributed open-source version control tool. Developers use Git to collaborate their work and control program versions.
Git commands
Following is a list of frequently used Git commands and how to use them.
git init
Create a local repo in your local machine.
git init
git remote add origin
Link your local repo with a remote repo, for example, a Github repo.
git remote add origin [URL]
git clone
Create a local repo. Link the repo to and clone contents from a remote repo.
git clone [URL]
git pull
Update the code in your local repo and workspace by pulling codes from remote repo. For example, if you want to pull codes from the linked remote repo’s main branch, you should use git pull origin main
command.
git pull [origin] [branch]
git status
View the current status of local repo and workspace. This command can be used to view if there is any untracked files or modified files.
git status
git add
Add some files to the index. You can use git add -A
command to add all files to the index.
Note: Files in index are tracked files, which means they will be committed to local repo using git commit
command. If you want to add only one file to the index, use git add filename
command.
git add [options] [filename]
git commit
Commit file in index to local repo. Frequently used command is git commit -a -m "description"
, which can commit all tracked files to local repo with specific description.
git commit [options]
git push
Push codes to update a branch of a remote repo. git push origin main
can update your linked remote repo.
git push [origin] [branch]
git branch
Create a new branch from current branch in local repo.
git branch [branchname]
git merge
Merge a branch into current branch. If I am currently in main branch, git merge anotherbranch
can merge another branch branch to main branch.
git merge [another branchname]
git checkout
Change to another branch by git checkout [branchname]
.
git checkout [branchname]
Revert back to previous version by git checkout [version-hash]
.
git checkout [version-hash]
git log
View version log of the program. Version hash can be view by this command.
git log
Some cases
Here I listed several cases that people, especially beginners, may frequently encounter when they are using Git.
Q1: How to create a local repo, link it to a remote repo and update it with remote repo?
git clone
can do this for you. Simplygit clone
a remote repo.
More quick tips: Always pull codes from remote repo before you get down to coding.
Q2: How to delete one or some files in one branch but still keep them in another branch?
- rm [filename] in branchA.
- git add -A to make sure all files are tracked in this branch.
- git commit -am "comments" to commit changes to local repo branchA.
- git checkout main, and you will find that deleted files will appear in this branch.
More quick tips: rm -rf [directory] to remove a whole directory (recursively and without asking).