###### tags: `cheatsheet` # Git Cheatsheet ## Basics Terminal: ``` git init ``` ``` git status ``` Add the modified file into staged file: ``` git add [FILE] ``` Turn the tracked file into staged file: ``` git commit -m "msg" ``` Shows the commit logs: ``` git log ``` ## Remote Repository Download remote repository to local repository: ``` git clone [Repository URL] ``` Add a new remote repository: ``` git remote add [remote-repo-name] ``` View remote branches: ``` git remote -v ``` Download others repository ``` git pull [remote-repo-name] master ``` Push the local repository to others remote repository or own remote repository ``` git push [remote-repo-name] master ``` ## View previous commits ``` git checkout <commit-hash> ``` or ``` git checkout HEAD~<number> ``` This will lead to 'detached HEAD' state. We can simply switch back to master branch you were on before by ``` git switch master ``` or make a new branch and switch to it if we want to modify the file by ``` # Creates a new branch on the detached HEAD pointing commit, detached HEAD will be attached after this command. git switch -c newbranch ``` ## Undoing **Update previous commit.** ``` git add [forgotten-file] git commit --amend -m "Update message" ``` **Turn the staged file into modified file.** ``` git reset FILE ``` **Undo for specific commit.** ``` git reset <commit-hash> ``` or **undo for previous commit.** ``` git reset HEAD~1 ``` The commits will be gone, but the **file content won't change**. To **undo both the commits AND the actual changes in files**, use ``` # DANGER!! git reset --hard <commit-hash> ``` This actually **moves the branch pointer backwards, eliminating commits**. Thus, the history are unable to retrieve. Since collaborators might have the previous commits on their local machines, use **git revert** instead to avoid the problem. ``` git revert <last commit-hash> ``` Revert the changes specified by the fourth last commit in HEAD and create a new commit with the reverted changes. ``` git revert HEAD~3 ``` This will create a **brand new commit** which reverses/undos the changes from a commit. New commit message is required.