how to use git or Github?

CC(ChenChih)
Chen-Chih’s Portfolio Page
28 min readMay 7, 2022

Today I would like to write a post on how to use Github. I believe that if you’re writing code most people will know that it’s a version control tool. There are many types of tools, which include GitHub, GitLab, and bitbucket.

You can use two ways to use git: GUI and CLI command. In this post, I will use CLI command, because I think it’s important to understand the command.

Please keep in mind I might not cover all of the commands, but I try to cover the most useful commands that will be used. This post I will divide into these sections:

Part1:Download, and setup git environment

Part 2: Basic Command( git add, commit, push, and etc)

Part 3: Advance command (reset, revert, branch, merge, and etc)

Summary: wrap up everything

Basic command :

1. git init
2. git log /status
3. git add
4. git commit
5. git push
6. Clone
ignore file (.gitignore)
alias

Advance command :

1. HEAD
2. log
3. Branch (local)
4. Checkout vs switch (switch branch)
5. Remote Branch
6. Merge
7. Squash
8. cherry-pick:
9. Reset and Clean
10. Revert Commit
11. rewrite git history
12. Pull and Fetch
13 reflog:

Part 1 Environment setup

Step1:Download and install tool

git Desktop

If you are interested to use the GUI, you can download :

Above is the tool you can use for GUI part, without typing commands. Sourcetree is a good tool for beginners to show their commit’s in a better understanding graph way.

git command

Install Homebrew: $ /usr/bin/ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)
Install git: $brew install git

Step2: Environment Setting: Setup git configuration

After installing git, it should have .gitconfig , for the window should be under c:\Users\<username>\.gitconfig . Linux and Mac contain \user\<username>\.gitconfig

if.gitconfigfile not exist then create a name and username it will automatically generate a file that will contain the username and email like below:

Create your username and email address (you can create any email if you like). Please create it like this:

git config --global user.name "username"
git config --global user.email email@gmail.com
#option
git config --global color.ui auto
#option: use specific text editor
git config --global core.editor emacs # emacs for mac

After you create this file you can use this command to check the properties of the git configuration:

  • $ git config --global --list # show only global setting
  • $ git config --list # show all setting

After this you can start using git command, you can use git --version to check git command work or not.

Next step please go to the GitHub home page and register an account. Git is the version control system lool, and Github is hosting git services that manage repositories. For more detail please refer to this link.

Part 2 Basic command

Let's first understand git’s basic fundamental term and the flow before using the command.

Let's talk about this term first:

  • working directory or workspace: you can refer it can your local PC’s directory or file. You can also think as a document in your local C drive not yet shared on the cloud.
  • Staging: The stage is where git starts to track on file that's been added or modified. So if you add a file, it will detect the file added and unstage.
  • Local Repository: Is like saving a file in the local repository, and it will record in .git directory.
  • Remote Repository: Remote repository is our GitHub server, when we finish our code, we want to publish it online to let other developers or teams see it. You can also refer GitHub as cloud or google cloud where you put your file on the internet.

1. git init

Step 1: init git or create a local repo

The first time we want to create an empty directory, you can create any directory. Go inside the directory and enter git init this command, it will generate .git a directory that will record all your information. If you can see it, please enable the hidden folder for Windows, or use ls-al for mac or Linux users.

Note: You can do another way, create a empty repository on github and use the git clone command to download it, it will also have .git directory

C:\git_code\tmp>cd newtest
C:\git_code\tmp\newtest>git init
Initialized empty Git repository in C:/git_code/tmp/newtest/.git/

2. git log /status

Step 2: check status and log

This two commands will use quite often to check your current local status and commit id.

  • git status: Get information about files and changes, or check file stage or not.
  • git log: will check your commit information, and will discuss more in advance part.
C:\git_code\tmp\newtest>git status
On branch master
No commits yet
nothing to commit (create/copy files and use “git add” to track)
C:\git_code\tmp\newtest>git log
fatal: your current branch ‘master’ does not have any commits yet

3. git add

Step 3 adding file and staging file

As you can see above we use git status occur nothing is been committed, so let's create a new file, and check git status to see the file stage status. It will be empty so we need to use git add . to staging file, you can also use git add <filename> , but only for one file. If you have multiple files please use . instead. Above this a picture showing your file status

Note: on git add with differnt option:

  • git add -A : stages all changes
  • git add . stages new files and modifications, without deletions (on the current directory and its subdirectories).
  • git add -u stages modifications and deletions, without new files
#step 1 create file 
$ touch 1.txt
$ ls
#Step 2 check status to see tracking list
1.txt
$ git status
On branch master
No commits yet
Untracked files:
(use “git add <file>…” to include in what will be committed)
1.txtnothing added to commit but untracked files present (use “git add” to track)
# Step3
$git add .
#Step 4 check status again
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: 1.txt

4. git commit

Step4 commit a file to the local repository

You will see when I use git status in the above example it keeps on showing no commit. So this time we will commit it, the commit command is: git command -m "message you want to commit"

#continue from above step4
#step5: git commit
$git commit -m "adding 1.txt"
#step 6 check git status again
C:\git_code\tmp\newtest>git status
On branch master
nothing to commit, working tree clean
#Step 7 check git log also
commit d55f91967b01be33d889ecb4322289b467fac115 (HEAD -> master)
Author: username <username@gmail.com>
Date: Sun Apr 24 10:43:21 2022 +0800

Note: We can also use this command to not change the commit message, but the commit ID will change, as below or go to below on rewrite git history

git commit --amend --no-edit

5. git push

Step 5 Push your local repository file into github server.

I will mention more about the remote in the advance section, right now I will only show you how to push it to the remote repository the easiest way.

After creating it, it will occur Quick Setup, please select the second command:

…or push an existing repository from the command line

We will need to create a remote repository, and push it to the server

5.1 Create a remote branch name, example: origin, and URL


#ssh git@github.com:<username>/<repository>.git
#https https://github.com/<username>/<repository>.git
#1. check git remote url is add or not, should be empty
git remote -v
#2 add remote branch and url
#git remote add <remote repoistory name> <url>
git remote add origin https://github.com/chenchih/newtest2022.git

If you type the wrong remote name(ex: origin), you can delete it or rename it by the below command:

Rename remotes branch : git remote rename <oldname> <newname>

Remove remote: git remote remove <name>

5.2 Create a local branch and push it to the remote repository

#check url is add or not 
mainC:\git_code\tmp\newtest>git remote -v
origin https://github.com/chenchih/newtest2022.git (fetch)
origin https://github.com/chenchih/newtest2022.git (push)
#3 add local branch and oush local branch to remote
git branch -M main #add local main branch
git push -u origin main #add main remote branch

git push -u origin master ( initial push required -u )

$ git push origin(remote working directory) master(local working directory)

#output
C:\git_code\tmp\newtest>git push -u origin main
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 207 bytes | 207.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/chenchih/newtest2022.git
* [new branch] main -> main
Branch 'main' set up to track remote branch 'main' from 'origin'.

-u flag push is used to set upstream. After setting the upstream via git push -u origin master, next time it will renmeber your last push remote server, you don't have to type git push origin maings You can just type in git push that’s enough.

5.3 check branch

you can use this command to check remote branch exist or not :

  • git remote -v: see if your git remote URL is added or not
  • git branch -a: see all branch, both local and remote branches is been added or not
  • git branch -r: for remote branch only

After this, you know the basic part of the git command, but there are more complicated commands in gits such as branch, merging, and more. The basic is able to help you understand it.

6.Clone

I think clone is a really important command you should know also. It’s to download the git repository from the GitHub server. As you remember that in the beginning, we do git init , and then we push to the remote repository and add the git URL. Actually, we can create a repository on Github, and it will automatically generate git init for us. After it generates, we can use the clone command to download it to our workspace.

How is the command work: git clone https://github/<username>/xxx.git . Isn’t the URL seem similar in the beginning we add the remote URL in Step 5. Basely it’s to download from server to local workspace, and in step 5 we upload our file into the server.

We can do this:

git clone https://github/<username>/xxx.git

also, we want to download with another name we can do like this:

git clone https://github/<username>/xxx.git newfile

Note: please keep in mind when you clone, it only clones the default main. If you want to clone the branch please refer to the remote section(Switch to a remote branch).

ignore file (.gitignore)

Sometimes if we don’t want to upload a specific file to the remote repository, we can use this file, and add a related file type to it. For example, if I have a .txt If and don’t want to upload it to the server, then I will add *.txtand it will ignore this file, and not upload it to the remote repository.

Window or Mac will often have DS_Store, but if we don’t want it to add to the remote repository server, we can add it in the .gitignore file.

Step1: create a .gitignore file like this and add the file you don’t want to upload to the git server. For example, text files ignore, so all text files in the directory will not be uploaded to the remote repository.

# text file 
*.txt
# OS generated files
.DS_Store
.DS_Store?

Step2: let's add a text file touch note.txt

Step3: push to the remote repository

Step 4: go to GitHub and check

alias

I think you should know how to setup alias , an alias is some shortcut command we can customize by ourselves. For example, git push we can use git p for git push something like that. In the advanced part, there’re more complex commands, alais that will help us efficiently on using the git command.

How to use it? We can also create alias in .gitconfig , like this :

[user]
name = my name
email = me@example.com
[core]
editor = vi
[alias]
aa = add --all
bv = branch -vv
ba = branch -ra
bd = branch -d
ca = commit --amen

you can refer to this link or use the command line to add as below:

$git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.st status
$ git config --global alias.ci commit
#show log oneline with graph
$ git config --global alias.log log --oneline --graph
$ git config --global alias.dog "log --all --decorate --oneline --graph"

So I have set git status as st. So instead of adding git status I can just use git st .

Part 3 Advance command

1. HEAD

HEAD is used to represent the current snapshot of a branch, the default match will point to the master branch or the last commit. The HEAD command is used in many different commands which include, log , reset , checkout , and more, so it’s important to know what’s the HEAD.

Head command you will see often people use ~or ^, these two symbols are actually the same. We will place N( ~N or ^)with it, which n is the last commit hash.

Last fifth commit : HEAD~5 or HEAD^^^^^ .

2. Log

Log is the most often used command to check your commit status or ID/HASH to revert or reset. The most common log I use are:

  • git log will show all detail logs, which is not quite easy to see
  • git log --oneline will only print the commit message and hash
  • git log --oneline HEAD~N : print the last N commits log
  • git log --oneline --graph will show your commit and branch in graph mode

3. Branch (local)

The default branch use master or main (new master called main). If you want to create another branch you can use checkout or switch this is a new command to replace checkout. You can think checkout=restore+switch

Why do we need to add a branch? The reason is that we will not only have one developer write a code, or not only one version of code is the final version. We will keep on updating and changing, so I will put these codes in another branch, until the final version is ok, then release it.

The master branch is like the final version of the code release, and the branch might be the draft, something like that.

  • Check Branch: git branch

We can check the current or local branches using: git branch for only local branch, or use -a for all branches or -r for a remote branch

  • Create new branch

This command only allows you to add a branch but will not allow you to switch branches. git branch <branchname>

  • Create and switch to a new branch

This command is been used most often, to create and switch to a new branch, compare to the above you have to switch by yourself. Command as below:

git checkout -b <branchname> or git switch -c <branchname>

  • Delete local Branch

You can delete a branch by using $git branch -d <branchname> ,

-d flag merge branch, -D flag not merge

Remove local Remote branch (remote will not remove)

git remote remove origin

4. Checkout vs switch (switch branch)

Let's talk about these two commands, which both can create and switch branches. The differences between both are: switchis only able to move from branch to branch, but checkoutcan move to different branches and also move the head to commit hash. I will talk more about checkout on restore and reset section.

  • checkout: This command allows you to add and switch branches, by adding -b flag. It also allows us to move our heads to specific positions to restore our commit ID. I’ll mention it in the restore and reset section.
  • switch: is a newer command which only allows you to add and switch branches. It will not allow you to restore a committed file, but you can use the new command restore . We can also use the switch - command. This command will record your previous branch you can switch by using the without adding the branch name.

Examples: Checkout and switch with the revert commit

Step1: let’s create three commit message

$mkdir checkout_example
$cd checkout_example
$git init
$touch 1.txt
$git add . && git commit -m "add 1.txt"
$touch 2.txt
$git add . && git commit -m "add 2.txt"
$touch 3.txt
$git add . && git commit -m "add 3.txt"
$git log --oneline

Step2 move to a specific commit hash or HEAD

So let’s move two commits back git checkout HEAD~2. Let's check the log, again, it moves two-step backward. The previous commit is not gone, it’s just the pointer of the head moving backward.

Step 3 restore the commit of the HEAD

so let’s restore our head to the original commit : git checkout - .

Step4 uses the switch method will not work

If you use the same method with switch command will not work. The switch command only allows us to switch branches but is not able to move commit hash or head.

Examples for creating, switching and deleting branches:

#1. create amd switch newbranch1 
$git checkout -b newbranch1
#or
$git switch -c newbranch2
#2. check current branch
$git branch
main
* newbranch1
#3. switch to master or main
$git switch -
$git branch
C:\git_code\tmp\newtest>git branch
* main
newbranch
#4. delete branch
$git branch -d newbranch1
Deleted branch newbranch1 (was 894b6de).
#5. check branch
$git branch
* main

5. Remote Branch

In Part 1, I have mentioned adding and pushing the master or main branches on both local and remote repositories. In this section, I will cover creating new branch and deleting the remote branch.

#1. check git remote url is add or not, should be empty
git remote -v
#2 add remote branch and url
#git remote add <remote repoistory name> <url>
git remote add origin https://github.com/chenchih/newtest2022.git

Add and delete the remote repository

Step 1: add a new local branch:

#checkout method
git checkout -b newbranch1
#or
#switch method
git switch -c newbranch2

Step 2: push to server

In the basic section I have mentioned adding a remote branch and URL, if you haven’t added them, please add them. Without the remote branch and URL, you’re not able to push to the server.

Let's recap what we learn before adding the remote branch name and URL as below:

#1. check git remote url is add or not, should be empty
git remote -v
#2 add remote branch and url
#git remote add <remote repoistory name> <url>
git remote add origin https://github.com/chenchih/newtest2022.git

If you have already added a remote URL, please skip the above command, and type the below command or git push , will occur error, and it will tell you there’s no upstream branch, as below message:

fatal: The current branch newbranch1 has no upstream branch.
To push the current branch and set the remote as upstream, use

git push — set-upstream origin newbranch1

so please type below upstream command:

Syntax: git push --set-upstream <remote repository> <branch-name>

git push --set-upstream origin newbranch1

Step3 check branch

git branch -a , newbranch1 will occur in remote

Step4 Delete remote branch

git push origin --delete newbranch1

You can also use this shorter command :git push <remote> :<branch>

Step 5 Check remote branch is deleted or not

git branch -r , local remote will be deleted

Switch to a remote branch (If you’re local don’t have a remote branch)

If you have another computer, if you clone git repository, it will only clone the master branch. If you want the remote branch, you can use it below.

git branch -a #list all branch, your remote branch is not there
git checkout origin/test #test is my remote branch
git switch — #switch to master
git switch test #remote branch appear

Remove local remote branch (remote will not remove)

git remote remove origin

Rename branch name

  • remote branch name

git remote rename <oldname> <newname>

git branch -m <oldname> <newname>

Additional information: fetch --prune.

The git fetch --prune the option will help to automatically synch from the remote and local branches. For example, if you delete from a remote branch, you pull it, but the local still has a remote branch, this time you need to use this command.

#Step 1 add new branch and push to remote server 
git checkout -b v2
touch 111.txt
git add .
git commit -m "add 111.txt"
git remote add origin https://github.com/chenchih/newtest2022.git
git push --set-upstream origin v2
git branch -a
#step 2 check remote branch
git branch -r #or -a
# master
#* v2
# remotes/origin/v2
#Step3 go to github page and delete v2 remote branch
#step 4 go to local repository and pull
git pull
git branch -a

As you can see I already delete the remote v2 branch, but the local side still exists remote branch. So this time, I have to use this git fetch --prune command to sync

6. Merge

After knowing how to create a branch it’s time to know how to merge branches. Merge actual means two branches merge together into one branch, so the final release code is master, and all the code in another branch must merge to master.

There are many types of merging, the most common merges are--ff or — ff-onlywhich is FAST Forward, --no-ff No Fast-Forward and Rebase.

I’ll also introduce these two commands which need to use rebase or merge to take effect which are: quash , and cherry-pick .

Syntax: git merge [--ff | --ff-only | --no-ff] <branch-name>

  • FF: linear merge

•Creates a new merge commit

•No new commits on master

•Linear History

By default, the git merge command is a fast-forward merge — -ffmethod: git merge <branchname> which is equivalent to git merge --ff <branchname> . Basely FF simply moves the source branch pointer to the target branch pointer without creating an extra merge commit, so as below you can see that my branch Feature merges to master, the c moves up to master without creating a new commit.

There is some situation you can not use the FF merge method when your master is ahead of your branch, such as the below flow:

So as you can see D (master) which is ahead of branch feature C, so this is not allowed, so typically when you use git merge it will automatically change to NO-FF method. However, you can force it to FF method but will occur an error message.

Let me show you an example:

#Step 1 add file in master branch
touch 1.txt
git add .
git commit -m "Master add 1.txt
touch 2.txt
git add .
git commit -m "Master add 2.txt
#Step 2 add new branch develop
git switch -c develop
#Step 3 add new file in develop branch
touch 3.txt
git add .
git commit -m "Develop add 3.txt
#step 4 switch to master branch
git switch -
#step 5 add new file
touch 4.txt
git add .
git commit -m "Master add 4.txt
#Step 5 merge to develop will change from linear to recursive
git merge develop

let force it to merge in linear mode only: --ff-only

#reset to before merging
$ git reset --hard HEAD~1
#merge force FF-only
$ git merge --ff-only develop

As you can see it will occur Error not allowing you to do FF method, if you don’t want to use Recursive mode, then you can instead use the rebase merge method.

  • NO-FF: Recursive merge

•Create new commit

•No new commits on master

command:git merge --no-ff

As you can see below picture, the No-FF allow you to see the history of merge, but when you have too many developers it will be messy and hard to read. Basely when you merge back using no-ff it will add a new commit.

Example for no--ff, use previous example:

#Step 1 add file in master branch
touch 1.txt
git add .
git commit -m "Master add 1.txt
touch 2.txt
git add .
git commit -m "Master add 2.txt
#Step 2 add new branch develop
git switch -c develop
#Step 3 add new file in develop branch
touch 3.txt
git add .
git commit -m "Develop add 3.txt
#step 4 switch to master branch
git switch -
#step 5 add new file
touch 4.txt
git add .
git commit -m "Master add 4.txt
#Step 5 merge to develop will change from linear to recursive
git merge develop

So as you can see if you’re Recursive Merge, it will split out the branch. You can see the history of the commit, but when we have many developers it will be hard to see.

  • REBASE: linear merge

Rebase will re-write the project history by creating a new commit for each commit in the original branch. So as below you can see the original C and D merge together which will create a new commit with a new ID.

command : git rebase <branchname>

As you can see after rebasing from C to D, the D is not the original D, you can see the D’s commit ID has changed.

7. Squash

Squash: combined multiply commits into one commit

Squash is combined multiply commit into one commit, as you can see the below, CDE is combined into a new commit. If there are too many commit messages or too messy commits, squash is the best option, it combined all the commit into one commit, and you can either rebase or merge it into master.

Why? To keep your git history tidy and easy to read. The only disadvantage is you will lose commit. Another reason might be you commit too often.

There’re are two types of squash:

- squash with interactive rebase: git rebase -i HEAD~N

- squash with merge : git merge --squash <branch-name>

- squash with merge, need to commit by yourself (less control)

Let me show you how it works if we have a branch called: new feature, and with three related commit logs, as you can see picture below.

I can merge with the squash method, as this command(please switch to master first) : git merge newfeature --squash . As you can see after the merge with squash, go to git status , the file is added in staging. So we have tp to commit by ourselves to take effect.

Note: if you don’t merge, and switch to another branch this effect will not take effect.

The difference between original merge and merge with squash, merging with squash will not have all the branched commit messages, it will only have one commit that you last committed. But the original merge will have all the commits you commit in the new feature branch and merge it into master. This will let the master branch be tidy. Please refer below picture to be more clear.

- squash with interactive rebase git rebase -i HEAD~N

Squash with interactive mode has much control, compared with the previous one(merge squash). There are many options to it, I’m only showing some of them.

Command: git rebase -i HEAD~N or git rebase -i <commut id>

There are many rebase-interactive options as below, I am showing only squash here. I will mention some examples of these options, but not all, please refer to rewrite git history below for more description. The option includes as below:

Step 1: switch to newfeaturebranch and use the git rebase -i HEAD~3

So what we are doing is we want to take the last two commit and combined them into the first commit.

Step 2 edit commit

After executing the command will pop edit mode with a different option, we will use squash. It will pop and have the last three commits, and you can see pick it in front of each commit id.

Press i to insert, change the pick to squash for the last two commits, what it will do is combined the last two commits into the first commit.

After changing it press esc + wq to save and exit

It will pop another edit screen, please type your commit message, you can leave as default is ok also. After changing it press esc + wq to save and exit.

Step 3 check out log, and it will squash from 3 commit into 1 commit as below

So please look at the commit message, it’s changed from the original commit message add 1.txt, then I change it to squash my commit. Also original we have three commits, it squash commit into one commit.

Step 4 you now can merge or rebase to master

After rebasing it, we need to merge it from the master.

git switch #switch to master
git merge newfeature

8. cherry-pick:

choosing a commit from one branch and applying it to another branch. If you have a specific commit you want to merge to master, then cherry-pick is the command you need to use or know.

Syntax:

single commit: git cherry-pick <commit-hash>

multiply commit: git cherry-pick <commit-hash> <commit-hash>

So we are able to choose single or multiply commit; for multiply commit, we just have to add space between it.

Step on how it works:


#step
#Step1: create a new commit in master
#Step2: create a new branch
#Step3: create commmit
#step4: check commit id you wants to merge to master
#step5: switch to master
#Step6: git cherry-pick fbfd048 #will merge this commit to master

For example, if I have a log like this:

after cherry-pick move specific commit to master:

8. restore vs checkout: revert back from the stage

Restore and Checkout is used to undo the changes made to a file such as a revert back from the stage to unstage, or to the last commit.

  • checkout vs restore (restore stage to workspace)

revert from stage to working area:

checkout: git checkout <filename>

restore:- git restore —staged <filename>

  • Checkout method to revert from stage

If you want to move the commit hash, either use the checkout or restore command. Both Checkout and restore are also able to revert the file to unstage.

Checkout other commands:

git checkout <filename> #revert from stage to unstage

git checkout -- <filename> revert back to workspace

git checkout -- .

git checkout <commit id> #move head to specfic commit id

git checkout - #remove to original status

$touch 1.txt
$git add . && git commit -m "add 1.txt"
$touch 2.txt
$git add . && git commit -m "add 2.txt"
$touch 3.txt
$git add . && git commit -m "add 3.txt"
$git log --oneline
#####################################
$cat 1.txt #file is empty
$vi 1.txt #add hello world
$git add .
$git status
$git checkout head 1.txt #it will revert into empty file
  • restore method to revert from stage

--stage :(Unstage files)Removes the file from the Staging Area, but leaves its actual modifications untouched.

--source: Restores a specific revision of the file. The source option is used to restore a file from a particular commit.

let us the same scenario with the restore command from the staging area to the working area: git restore --staged <filename>

$vi 1.txt #add hello world
$git add .
$git status # staging area
#move file from staging area to working area
$git restore --staged 1.txt
$git status #move to working area
#revert the file again
$git restore 1.txt
$cat 1.txt #file will be empty

So as you can see reverting file restore and checkout does the same thing. If you're not clear please refer to the git-flow below or the top picture on the git-flow.

  • restore with a source to revert to the last commit

git restore --source <commit id> <filename>

git restore --source <HEAD~N> <filename>

git init 
touch 1.txt
vi 1.txt #add hello.txt
git add .
git commit -m "add hello to 1.txt"
cat 1.txt #hello
vi 1.txt #add wold.txt
git add .
git commit -m
cat 1.txt #hello world
$ git restore --source adcacb6 new.txt #restore to hello
cat 1.txt #hello
  • other restore commands:

git restore one.txt two.txt

git restore .

9. Reset and Clean

I would like to introduce the Reset and Clean commands.

reset this command is used to restore your commit.

clean will recursively remove files, but only when it’s not staging

reset

There are three different types of reset: hard soft , and mixed . Default reset used mixed . Please refer below picture to be more a clear understanding.

Syntax:

default is mixed: git reset

git reset #default mixed

git reset [--hard| --soft] HEAD~N

git reset [--hard| --soft] <commit id>

  • hard reset file: will restore everything
  • mixed reset(default):

unstage file: don’t change

stage: move to unstage

commit:move to unstage

  • soft reset:

unstage file: don’t change

stage: move to don’t change

commit:file move to stage

Compare HARD VS SOFT

Clean

you can use -n flag to check which file will be deleted, and use -f flag to delete it. Example:

touch hello.py
$ git clean -n
Would remove hello.py
$ git clean -f
Removing hello.py

10. Revert Commit

recover to the last commit, and commit with a new commit message

Syntax: git revert <commit id>

  • revert-after commit
  • n flag: will recover back without committing, you have to commit yourself

11. rewrite git history

As you already know the concept of rebase-interactive mode, there are some more options that we are able to rewrite our commit message. I will share some of them, but not all.

amend : allow us to rewite only last commit message

If you think your last commit message has some typo or want to edit it, please use this command:

edit last commit: git commit --amend

commit the same commit message : git commit --amend — no-edit . As you can see you can commit using the command, and the commit message stays the same but the commit ID changed.

rebase interactive: reword option (edit commit message)

So since amend can only edit the last commit message, if you want to edit the specific message, you have to use the reword option, which will edit any commit message.

$git rebase -i HEAD~3
#change pick to reword

rebase interactive: drop option (DELETE commit)

If you want to delete a commit message you can use the drop command

$git rebase -i HEAD~3
#chnage pick to drop to delete

12. Pull and Fetch

When we have two developers, clone the repository into the local workspace. The first developer push code to the remote repository and the second developer doesn't know there is a new update, so when he pushes will have conflict.

To fix the conflict, you can use git pull it will update the code to the local repository with the latest update.

Fetch does the same things, but the only difference is fetch will not merge to master. Fetch will only download, without merging, you have to merge yourself.

You can think like this :

PULL: download and merge (fetch+merge)

Fetch: download without merge

git fetch

The purpose of fetch is to download the file, but not merge it. You can use the git diff compare the different , and it will not write the file

Step1: clone repository

Step 2: edit repository on github

Step 3:go to local workspace and use the fetch command: git fetch

Step4: use git diff main orgin/main and check difference between local repository and remote repository

Step 5: user git merge orgin main or rebase to merge or rebase the file changed.

git pull

git pull will automatically download and merge, which will overwrite the file. command is: git pull . So when you update in server, but the local workspace uses the pull command, the file will be updated.

When we have a conflict we will use the pull or fetch command

13 reflog:

If you want to find all delete commit or reset commands, please use this command to find all your commit id. You can refer to this can all commit will be recorded there.

You just have to use git reflog , it will list all your commit log, and you can reset the commit id, that simply.

Summary

I know there are a lot of git commands I cover in one post, but I think there are still many commands I didn’t mention. I just want to cover the most useful command.

If there’s some description I mention that is not correct, please leave a comment. Git still has more complex commands, but in this post, I cover the most important one, and you can be able to use it in your daily life.

I will make a summary of all the commands I used, due to this article is too long.

edit or rewrite history-commit message

git commit — amend

git commit — amend — no-edit

git rebase -i HEAD~3

git revert <commit id> #-n flag need to commit by yourself

Log: (use often)

git log

git log — oneline

git log — oneline HEAD~

git log — oneline — graph

Branch

  • switch to remote branch (use often)

git branch -a #list all branch, remote branch not appear
git checkout origin/test #switch to remote branch(tesT)
git switch — #switch back to master or main
git switch test #switch back to remote branch will appear

  • rename branch

git remote rename <oldname> <newname>

git branch -m <oldname> <newname>

  • delete branch (use often)

git remote remove origin #remove local remote branch only

git push origin — delete newbranch1 #delete remote branch

git fetch — prune #will sync with remote server and delete local remote branch

  • check branch (use often)

git branch -r

git branch #local

git branch -a #all branch

  • switch branch (use often)

git checkout -b <branchname>

git switch -c <branchname>

git switch — #record last branch able to switch

  • add branch to remote (use often)

git remote -v #git remote url is add or not

git remote add origin <url>

git push — set-upstream origin newbranch1

merge (use often)

git rebase <branchname>

git merge — ff-only develop

git merge — ff <branchname> #same as git merge

git merge — no-ff

git merge newfeature — squash #squash multiply commit

git cherry-pick <commit-hash> #merge specfic commit from branch to branch

recover file and files

  • restore command:

git restore — source <commit id> <filename>

git restore — source <HEAD~N> <filename>

git restore — staged <filename>

  • reset command: :

git reset #default mixed

git reset [ — hard| — soft] HEAD~N

git reset [ — hard| — soft] <commit id>

git clean #only when not staging

  • Checkout command only move head

git checkout <filename> #revert from stage to unstage

git checkout — <filename> revert back to workspace

git checkout <commit id> #move head to specfic commit id

git checkout -

Reference

https://medium.com/@nmpegetis/git-how-to-start-code-changes-commit-and-push-changes-when-working-in-a-team-dbc6da3cd34c
https://www.themoderncoder.com/combining-git-commits-with-squash/
https://www.themoderncoder.com/rewriting-git-history/
https://www.cloudbees.com/blog/git-delete-branch-how-to-for-both-local-and-remote
https://stackoverflow.com/questions/61762147/why-does-github-reccomend-using-git-merge-ff-only-upstream-when-checking-ou
https://www.w3schools.com/git/git_revert.asp?remote=github
https://stackoverflow.com/questions/292357/what-is-the-difference-between-git-pull-and-git-fetch
https://medium.com/towardsdev/git-commands-you-must-know-d217bf710502
https://linuxhint.com/git_cherry_pick/

--

--

CC(ChenChih)
Chen-Chih’s Portfolio Page

I self study technology, and likes to exchange knowledge with people. I try writing complex tech blog into simple and various ways for people to understand.