2 minute read

What is Git

Git is a distributed open-source version control tool. Developers use Git to collaborate their work and control program versions. git

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.

  • git clone can do this for you. Simply git 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?

  1. rm [filename] in branchA.
  2. git add -A to make sure all files are tracked in this branch.
  3. git commit -am "comments" to commit changes to local repo branchA.
  4. 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).

Reference

Updated: