Notes on Git Basic Usages

After taking the CS101 and CS2103, I find out that git is very useful. It can easily helps me record my edition of the file and help me revert it. But I am always forget the command of different usages, so hope this post can be like a note for me to remember. :)

git branch:

You can think of them as a way to request a brand new working directory, staging area, and project history. New commits are recorded in the history for the current branch, which results in a fork in the history of the project.

  1. List all of the branches in your repository: git branch
  2. Create a branch called abc: git branch abc
  3. Delete a branch abc in a safe mode: git branch -D abc
  4. Switch current branch to abc: git checkout branch abc
  5. Create and switch to branch abc: git checkout -b abc

git revert:

The git revert command undoes a committed snapshot. But, instead of removing the commit from the project history, it figures out how to undo the changes introduced by the commit and appends a new commit with the resulting content. git revert HEAD

Discard changes

  1. Before git add
    1. Discard files For a specific file: git checkout path/to/file/to/discard For all files: git checkout -- . (there’s a period at the end)
    2. Discard new files To show what file will be deleted: git clean -f -n To delete files: git clean -f To delete directories: git clean -f -d To delete ignore files: git clean -f -X To delete ignored and non-ignored files: git clean -f -x
  2. Undo git add Unstage a specific file: git reset HEAD Unstage all files: git reset HEAD

  3. Undo git commit git reset --soft HEAD~1

  4. Reset to specific commit git reset --hard [commit hash]

  5. Force push local repo to remote repo, remote repo will be the same as local repo git push origin master --force

Merge some commits from a pull request

git cherry-pick <"commit hash">

Adding an existing project to Git

  1. Create a repository on git;
  2. cd to the directory that is going to be uploaded to git;
  3. Initialize the local directory as a Git repository: git init;
  4. Add the files to your new local repository: git add .;
  5. Commit the files: git commit -m "First commit";
  6. Add the remote repository’s URL where your local repository will be pushed:
    1
    2
    3
    4
     git remote add origin [remote repository URL]
     # Sets the new remote
     git remote -v
     # Verifies the new remote URL
    
  7. Push the changes to the remote repository: git push -u origin master.

Resource: Atlassian Git Tutorial