Open CheatSheet Back To List Next Tutorial

Beginning Git Tutorial (Video Tutorial)

Beginning Git Tutorial

Intro

  • This is the first in a series of tutorials that includes Beginning Git, Intermediate Git, Beginning GitHub, Intermediate GitHub, and the Markdown language for Readme files.
  • In this tutorial we will cover beginning Git. You should get comfortable with the material in this tutorial before moving on to Intermediate Git or GitHub.
  • To demonstrate the Git concepts we will be creating a project called git-demo. It is recommended that you code along with the tutorial.
  • For reference, the finished code is available at github.com/LearnByCheating/git-demo and the Readme file tells you how to follow along.

Read it, watch it, do it, review it:
  • There are both a written and accompanying video version of this tutorial. The written version has timestamps under the headings that align with the video version of the topic.
    • Read it: For each topic heading, first read the topic. 
    • Watch it: Then watch the associated section of the video.
    • Do it: Then follow the instructions to replicate the steps on your computer.
  • The CheatSheet has a major category that aligns with this tutorial.
    • Review it: When you are done with the whole tutorial, do the two Beginning Git exercises. They repeat the steps from this tutorial without the explanations so you can do them quickly. One exercise uses only Git commands, the other uses the VS Code Source Control sidebar's graphical user interface.
    • Open the CheatSheet and review the Beginning Git category which includes all the topics from this tutorial. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 



What is Git?

[0:00 Video timestamp]

  • First, what is Git?

  • You can read about it on the website git-scm.com. Scm stands for source code manager. Git is a tool to manage your source code. While there are other tools for that purpose, Git is the industry standard.

  • The way Git manages your source code is through a Version Control System. A Version Control System:
    • Allows multiple developers to work on the same project simultaneously.
    • Prevents changes from being overwritten.
    • And maintains a retrievable history of each version.

  • Git is a distributed system rather than centralized. That means collaborators check out the full project from the central repository, work on their changes independently, then the changes are reviewed and committed back to the central repository.

  • You can use Git to organize your code:
    • First create the Git repository for your project.
    • Create a separate branch for each major feature.
    • Make a commit every time you complete a coding task.
    • Add a tag to your important commits when you complete a feature, make new release, or finish a major bug fix.



Install or update Git

[1:24 Video timestamp]

  • To see if you have Git installed on your computer go to the Command Line of your Unix shell application such as the Terminal app on Mac. Then enter which git
    • If it is installed it will return the location of the executable file.
  • Or you can enter git --version to get the version that is installed.

  • You can compare that with the latest version available from their website: git-scm.com
  • Git uses semantic versioning so the first number is the major version, then the minor version, then patches. 
  • If Git is not installed or is in need of an upgrade you can click the download button. Then follow the instructions. 
  • For Mac there are several options for installing Git. 
    • If you have XCode installed it includes a binary version of Git.
    • On the downloads page of their website there is a link to an installer program but it's not always up to date. 
    • If you use Homebrew for installing applications, there is a Homebrew option to install or upgrade Git. Enter: brew install git 



Documentation/Help

[2:33 Video timestamp]

  • To get the documentation on a command, from the Git website home page, click on "Documentation".
    • In the search box, enter the command name that you want information on such as "config".
    • It will pull up the closest matches. If you click on the top result: "git-config", it will take you to the documentation for the Git config command.
  • You can also get the documentation on a Git command from the command line. Just enter git help then the command name:
git help config
  • Git commands that return a lot of text like help, log, show, and diff use the Unix paging program called "Less" for displaying the data in the terminal.
  • To navigate through the data use the following keys:
    • DownArrow and upArrows go down or up one line.
    • d goes down half a page. u goes up half a page
    • f or space will go forward one screen. b will go back one screen.
    • Upper case G goes to the end of the document, lower case g goes back to the beginning.
    • To search for a word enter Slash and the word /search-term and it will take you to the first occurrence of that word. 
    • Press n to go to the next occurrence. Capital N goes to the previous instance.
    • q quits the Less program.



Configure Git

[3:55 Video timestamp]

  • When you initially set up Git on your machine you should add some configuration variables. You can set them with the global flag so they apply to all your local Git repositories. 
  • Global variables can be overridden for a specific local repository by adding the Git config variables on the local repository without the global flag. 
  • To set the name and email variables enter git config --global user.name "your-name".
  • Similar for email: git config --global user.email "your-email".
  • Your name and email will be added to the metadata of each Git commit that you make. This is important on collaboration projects.

  • At the time of this tutorial the default name of the initial branch is "master". GitHub uses "main" which causes a conflict. Git will be changing the default name in a future version.
  • So if it hasn't been done in your version of Git yet, add a config global to change the default to "main".
git config --global init.defaultBranch main

  • To view one of the global variable values, run the command without the value argument, like:
git config --global user.name  
  • Or to view all git config global variables, run
git config --global --list

  • You can use git config to set aliases to shorten long commands that you use frequently. Use the below format:
git config --global alias.name 'git command' The to run the command: git alias
  • For example, below is an alias for a oneline log command that we will cover shortly:
git config --global alias.olog 'log --oneline' 
Execute it with: git olog

  • To remove a global variable or alias use the below command:
git config --global --unset variableName  
  • For instance to remove the global alias we just set, enter:
git config --global --unset alias.olog 

  • If you are using VS Code you can set it as your default text editor for Git with: 
git config --global core.editor "code --wait"



Set up a Local Git Repository

[5:43 Video timestamp]

  • Now that you have Git installed and configured, let's create a simple project that we'll use to demonstrate Git.
  • The pwd Unix command will show the present working directory (i.e., the directory you are currently in)
pwd 
  • Use the cd command to change directories until you are in the directory you want to work in. Then create a directory called git-tutorial to hold the Git examples in this tutorial series. You can use the Unix mkdir command for that:
mkdir git-tutorial
  • Cd into it, then create another directory that we'll use for the rest of this tutorial called git-demo, then cd into that.
cd git-tutorial 
mkdir git-demo 
cd git-demo 



 VS Code Source Control sidebar (Git integration)

  • If you use Visual Studio Code as your text editor, open it to the empty git-demo project (not git-tutorial).
  • One of the advantages of VS Code is its tight integration with Git and GitHub. Most Git commands can be done either from the command line or with VS Code's built-in Source Control sidebar. We'll be using both throughout this tutorial series. 
  • Another advantage is VS Code has an integrated Terminal panel that you can open inside your text editor. Click the Terminal menu at the top > New Terminal.
  • If you are not using VS Code, just skip over the VS Code toolbar sections.

  • To open the Source Control sidebar just click the Source Control toolbar on the activity bar: 
    •  At the top right of the sidebar are three dots. If you hover over them it will reveal a label: Views and More Actions... Clicking it will display a drop-down menu with multiple Git-related actions. For the rest of this tutorial series we will refer to this menu with:
    • ⋯ > Menu item > Submenu item 
  • To go back to the Explorer sidebar, listing the file tree, click the Explorer toolbar: 


Initialize a Git Repository

  • First you need to initialize a local git repository. You can either: 
    • Open the Source Control sidebar > Then click the Initialize Repository button. 
    • git init Or open the Terminal > enter the git init command. All Git commands start with "git".

  • View the .git repository:
    • You can see the git repository in the Mac Finder app, or the Windows File Explorer.
    • It is in the project directory as a hidden file. Hidden files have a dot in front of the file name. 
      • To show hidden files on Mac, enter Shift+Cmd+.
      • To show hidden files in Windows: 
        • Open File Explorer from the taskbar.
        • Select View > Options > Change folder and search options.
        • Select the View tab and, in Advanced settings, select Show hidden files, folders, and drives and OK.
    • Then if you expand the git-demo folder you can see there is a folder called .git. This is the project's local Git repository that we just initialized. 

  • Now let's add some files to our project.
  • Add a text file to the git-demo project called app.txt with just a single line that says "This is a demo app to learn Git." 
app.txt
This is a demo app to learn Git.

  • Unsaved files have a white circle after the file name in the tab at the top of the editor. You must save new files or file changes before committing them to Git.



.gitignore

[7:35 Video timestamp]

  • Add another file that we will exclude from Git called ignoreme.txt with a line that says "Git ignores this whole file." And save it.
ignoreme.txt
Git ignores this whole file.

  • Add another file called .env (begins with a dot) with text: "Sensitive Information Goes here".
.env
Sensitive Information Goes here.

  • Add a file called .gitignore in your project root. It has a dot in front of the name and does not have a file extension.
  • List the files and directories that you want to exclude from Git in the gitignore file.
  • Exclude files that aren't relevant to the project such as the MacOS .DS_store files.
  • Exclude large files and directories that don't need to be tracked. For instance Node.js stores third party packages in the node_modules folder. You don't control changes to those files so you can exclude them from your Git repository.
  • For projects that will be stored in an external repository, you want to ignore files from Git that contain sensitive information like passwords. For example, if you store sensitive information for your project in a file called .env, then add that to your .gitignore file.
  • Add the ignoreme.txt file. Your .gitignore file should look like the below:
.gitignore
.DS_Store
.env
ignoreme.txt

  • Save the .gitignore file. Notice after you save it, that the file names in the Explorer panel on the left turn grey. The file names are color coded. Grey means they are ignored by Git.

  • GitHub has example gitignore files for each major programming language. Those files will likely list a lot more files than you will have in your project. github.com/github/gitignore



Commits

[8:32 Video timestamp]

  • Let's make our first commit.
  • A commit stores a snapshot of project files at the time of the commit in the Git repository. Each file's code is compressed and stored in a binary large object (or blob). It also stores the meta information about the commit including the author name and email, the date, and commit message.
  • Besides the ignored files, we have two files that we want Git to track: app.txt and the .gitignore file. 
  • If you open the VS Code Source Control sidebar, the two untracked files are under the "Changes" heading.

  • Let's take a look at some diagrams:

The Git environment

[9:15 Video timestamp]

 
  • This is the Git environment. There is a local environment which means our project's local Git repository. And a Remote environment such as GitHub which we'll cover in a separate tutorial. 

  • Within the local environment, file changes can be in one of three areas.  When you add a new file, or modify an existing file, it is in the working directory. Git also calls this the working tree. These are the files you are currently working on for the next commit.
  • When the new or changed files are ready to commit, move them to the temporary staging area with the "git add" command. Or you can use the VS Code Source Control sidebar.
  • After you queue up all the files you want to commit in the staging area, commit them to Git with the git commit command. That moves the changes to the local git repository. At that point the working directory and staging area will be empty.


 Make Commit using the VS Code Source Control sidebar
  • Now let's stage our current changes using the Source Control sidebar.

Open the Source Control sidebar.

Stage and Commit Changes use one of the below methods:
  • Stage Changes: 
    • We added two files that we will be tracking with Git: app.txt and .gitignore. These are in our working directory. The Source Control sidebar lists them under the Changes heading. 
    • The circle 2 to the right of Changes means there are two new or changed files. 
    • You can move the files to the staging area in a few different ways:
      • + Click the + sign to the right of the file name to move it under the "Staged Changes" heading which means it's in the staging area.
      • + Or to move all files at once, click the + sign to the right of "Changes".
      • ⋯ > Changes > Stage All Changes Or stage them from the Source Control drop-down menu.
  • - Unstaged Changes: 
    • If the files are staged they will be under the Staged Changes heading.
    • To unstage them you can either:
      • - Click the minus sign to the right of the file name and it will move back to the working directory. 
      • - To unstage all files, click the minus sign to the right of the Staged Changes heading.
      • ⋯ > Changes > Unstage All Changes Or unstage them from the Source Control drop-down menu.
  • Commit Staged Changes:
    • To move the changes from the staging area to the local Git repository, you need to commit them. 
    • Enter message in box > ✓Commit Enter a commit message in the message box at the top of the Source Control sidebar. Since it's our first commit enter "First commit". Then click the ✓Commit button below it.
    • ⋯ > Commit > Commit Staged Or, instead of clicking the checkmark, you can click the three dots at the top of the side panel > Commit > Commit staged.
  • And now your git repository has its first commit. 
  • We will cover logs shortly, but to confirm the commit was made enter: git log



File States and VS Code file name color coding
[12:04 Video timestamp] 

Take a minute to understand the below diagram and table including.
It is recommended you come back to this section when you finish the tutorial to get a better understanding of it including:
  • The Git file states: ignored, untracked, tracked unmodified, tracked modified, and staged.
  • What Git area a file is in depending on the file state: n/a (no area), Working Directory, or Staged.
If you are using VS Code:
  • In the Explorer sidebar: How filename color indicates Git file state: green, white, yellow.
  • In the Source Control sidebar: what heading the file is in depending on the file state: n/a, Changes, or Staged Changes.



  • In the VS Code Explore sidebar the filenames are color coded depending on their file state.
  • In the VS Code Source Control sidebar untracked and modified files are grouped under Changes or Staged Changes. 
  • The below table shows the Git file states and how that relates to Git Area, filename color coding, and the Source Control heading.
File StateGit AreaVS Code Explorer
filename color
VS Code Source
Control heading
Ignored: In the .gitignore filen/aGrayn/a
Untracked: New file never committed to Git
  • Unstaged
  • Staged
-
Working Directory
Staging Area
-
Green U
Green A
-
Changes
Staged Changes
Tracked: Previously committed to Git
  • Unmodified: No change since last commit
  • Modified: Changes since last commit
  • Staged: File moved to staging area.
-
n/a
Working Directory
Staging Area
-
White
Yellow M
Yellow M
-
n/a
Changes
Staged Changes


CLI Make a Commit from the command line
  • For our second commit, modify the app.txt file by adding another line of text to it:
app.txt
This is a demo app to learn Git.
Second line.

  • And let's create a new file called file2.txt.
file2.txt
Some text.

Let's look at the file states:
  • File2.txt has not been committed yet so it is untracked, and color coded green.
  • app.txt was part of our first commit so it is tracked. But we modified it so the file state is modified, and the color code for modified files is yellow with an M after it.
  • The gitignore file has already been committed to git but has not been modified since the last commit. Tracked files that are currently Unmodified are color coded white.
  • ignoreme.txt and .env are in the .gitignore file so their color code is grey.
  • Now we can make the commit, this time using the git add and commit commands rather than VS Code's source control sidebar.

  • Open your Terminal app so we can use the command line.
  • If you are using VS Code, from the Terminal menu select New Terminal.

    There are two commands to make a commit:
    1. Add all untracked and modified files to the staging area. 
    git add . 

    • Use a dot . to move all files. 
    • Otherwise replace the dot with a list of the specific filenames you want to move separated by spaces.
    • Now all the changes are in the staging area. Looking back at the file tree, the untracked file2 is still green but the letter U has changed to A, indicating that it has been added to the staging area.

    2. Commit all the files in the staging area to the Git repository. Include a commit message after the -m flag.
    git commit -m 'Add file2'

    Log the two commits we have made so far:
    git log



    Commit message
    [13:38 Video timestamp]

    • The Git website does have some guidance on how to write commit messages: 
    git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project
    • These are recommendations not rules:
    • Start with a capital letter. Don't end with a period. Keep it short, under 50 characters. And use the present tense imperative mood, like telling you what to do. The message in our second commit was "Add file2".

    Detailed Commit Message:
    • You could add a more detailed message after the summary by adding a blank line after the message summary then your detailed message below that. To include bullet points use a hyphen. 
    • This is useful when working on a collaborative project, or to remind yourself of what you did.



    Stage and commit files in one step
    Let's create another file called file3.txt and save it.
    file3.txt
    Some text.

    To stage and commit the file in one step:
    • In the VS Code Source Control sidebar, enter a message in the message box at the top "Add file3", then click the Commit button. Then click Yes to confirm. Now it is staged and committed in one step.

    We now have three commits: git log

    You can also stage and commit in one command from the command line as well, but only for tracked files (that have previously been committed), not for untracked files.
    Don't enter this, but the command to stage and commit tracked files is: git commit -am 'Modify file x'



    Atomic Commits
    [14:42 Video timestamp]

    • How often should you make commits?
    • One recommended strategy is called Atomic commits.
    • Focus each commit around a specific change or feature, rather than a whole bunch of miscellaneous changes and updates. This lets you retrieve specific changes later if you need them.



    Status, Diff, Log, and Show commands

    • We will be printing a lot of info on the screen. To clear the screen at any time enter:
    clear
    On Mac you can enter Command+K


    Status Command: view status and changes since last commit
    [15:01 Video timestamp]

    • There are a few useful commands to use before making commits.

    • git status lists the status of any files changed since the last commit. Whether they are staged, unstaged, or untracked. 
    • We haven't made any changes since the last commit so it just says "nothing to commit" meaning our working directory and staging area are empty. From a file state perspective, all our files are tracked and unmodified.

    • Now let's add a new file called file4.txt with some text and save it. 

    file4.txt
    Some text.

    • The file is now in the working directory, and its state is untracked since it has never been part of a commit.

    • Now modify the app.txt file and save it. 

    app.txt
    This is a demo app to learn Git.
    Second line modified.
    Third line

    • It is now in the working directory and its file state is modified.
    • If you run git status again: git status 
    It will list app.txt as modified, and file4.txt as untracked. Both these filenames are color coded red in the command line, which means they are unstaged.
    • Add file4 to the staging area: git add file4.txt 
    • If you run git status again, now file4 is ready to commit. And colored green in the command line.



    Diff command
    [16:21 Video timestamp]

    • If you want to see all file changes made since the last commit enter git diff. 
    • To see the changes for a specific file, Append the file path to the command: git diff app.txt
    • The changes are color coded by line. Red is the previous version of the line, green is the modified version.

    • Add app.txt to the staging area: git add app.txt
    • If you run git status again, now both files in the Terminal are green and ready to commit.
    • Commit the changes to git: git commit -m 'Add file4'
    • In the VS Code Explorer sidebar, all the files are now white. So all files are now tracked and unmodified.



    Log command
    [16:57 Video timestamp]

    • The log command prints a list of commits for the current branch in reverse chronological order: git log
    • We have made 4 commits so far so they are all listed. 
    • The log shows some meta information about the commit, including the commit id, the author name and email, the date, and the commit message.
      • At the top, is the branch name (main). Head means that commit is the latest commit for that branch.

    • The commit id is both a unique identifier, and a security device. 
      • It consists of 40 hexadecimal characters. It is generated with a hash function that incorporates the meta and file information. If any data is changed, the commit id will be invalid.

    • To get the last 2 commits add dash 2 after git log: git log -2
    • If you want to see each commit as one line just add the --oneline option after git log: git log --oneline
    It will show the first part of the commit id and the commit message.
    • We can make a global alias for the command with: git config --global alias.olog 'log --oneline'
    Olog is the alias. The command it runs is the argument in quotes at the end.
    • Now you can enter git then the alias to print the logs on one line: git olog



    Show command

    [18:19 Video timestamp]

    • If you want to see the details of a commit, use the show command with the commit Id. Just copy all or the first part of the id (at least 4 characters) from one of the logged commits. git show commitID
    • It will show the meta info of the commit, plus the changes made in the commit.
    • In Git, "head" represents the latest commit. So to show the latest commit, instead of the commit id, you can enter git show head. It is case insensitive.
    • For one commit prior to the latest, add the hat symbol after head: git show head^
    • For 2 commits, or some other number, after head add the tilde symbol and the number.
    git show head~2 would be 2 after head, which is 3 commits ago.



    Branches

    [19:04 Video timestamp]

    • The last topic we'll cover in the Beginning Git tutorial is branches. 

    • It is a common practice in Git to use branches extensively.
    • A branch is a breakaway version of the project that focuses on a specific feature or fix. You can work on it independently, then merge it back into the main branch when you are done. Or discard it without affecting the main branch.

    • To see a list of all your project's branches enter: git branch 
    • You can see you only have one branch called main. Which is your default branch. The asterisk in front means that this is the branch you are currently on. 


    CLI Create branches using the command line

    Step1: Create a new branch called feature1.

    • To create a new branch and check it out run "git checkout -b" followed by the branch name, we'll call it "feature1":
    git checkout -b feature1
    • Now if you run git branch you can see there are two branches and you are currently on the feature1 branch.


    Step 2: Make file changes.

    • Create a file called feature1.txt and add some content.
    feature1.txt
    Some text.

    • Then modify app.txt by adding "Feature 1" text to it.
    app.txt
    This is a demo app to learn Git.
    Second line modified.
    Third line.
    Feature 1.


    Step 3: Stage and commit changes.

    • Looking at the diagrams, when you checked out the new branch you started with a clean working directory. With all unmodified files.
    • Then we created an untracked file, and modified an existing file. These changes are currently in the Working directory.
    • If you run git status it shows what branch you are on. And that you have an untracked file and a modified file that is not staged.

    • git add . will add all changed files to the staging area. The state of the two files is now "staged"
    • git commit -m 'Add feature 1' will commit the changes to the git feature1 branch. 
    • git status shows you are on the feature1 branch and there are no modified files in the working directory or staging area.
    • The two changes are now in the local repository and the state of the files after the commit are now unmodified.

    • To see the differences between the main and feature1 branches we can run: git diff then the branch names:
    git diff main feature1
    • The differences are shown in the Terminal.


    Step 4: Switch back to the main branch.

    • To merge the feature1 branch back into the main branch, you need to first checkout the main branch. Enter git checkout then the branch name:
    git checkout main
    • You can see the feature1 file you just created is now gone since we are back on the main branch, and the line I added to app.txt is also gone.


    Step 5: Merge feature1 branch into main.

    • Now enter "git merge" and the branch name.
    git merge feature1
    • Now the feature1 branch is merged into the main branch. The feature1 file has appeared and app.txt has the new line in it.


    Step 6: Delete feature1 branch.

    • Now we can either delete the feature1 branch or leave it if we expect to modify it more.
    • We'll delete it with git branch -d and the branch name, feature1:
    git branch -d feature1

    • git branch shows there is now just one branch, main.
    • git log -3 shows our last 3 commits. The head commit is from the feature1 branch that we just merged in.



    Create branches using the VSCode Source Control sidebar

    [22:21 Video timestamp]

    • Now let's add a branch using VS Code's Source Control sidebar.

    Step1: Create a new branch called feature2.

    Open the Source Control sidebar.

    Two ways you can create a new branch without using the command line:
    •  Click the dropdown menu at the top of the Source Control sidebar:
      • ⋯ > Branch > Create branch: Name: "feature2" 

    • Click the Status Bar main branch name:
      • Status Bar: The status bar is the blue bar at the bottom of the window. It contains information about the opened project. The current branch name is on the left side of the status bar.
      •  Click "Main" > Select Create New Branch > Enter: feature2


    Step 2: Make file changes.

    Open the Explorer sidebar.

    • Add a file called feature2.txt with some text.
    feature2.txt
    Some text.

    • And add a new line to the app.txt file.
    app.txt
    This is a demo app to learn Git.
    Second line modified.
    Third line.
    Feature 1.
    Feature 2.


    Step 3: Stage and commit changes.

    Open the Source Control sidebar again.

    • + Stage the changes by hitting the plus sign to the right of the Changes heading.
    • Enter message in box > ✓Commit Enter a commit message in the message box at the top of the left panel: "Add feature 2" and click the ✓Commit button to commit the changes.

    • In the terminal, git diff main feature2 will print the differences between the main and feature2 branches.


    Step 4: Switch back to the main branch.

    Use one of the below methods:
    • ⋯ > CheckoutTo > select main Use the Source Control dropdown menu.
    •  Use the Status bar branch section at the bottom: Click "feature2" > select "main" branch. The status bar will then show "main".


      Step 5: Merge feature2 branch into main.

      • ⋯ > Branch > Merge branch > Select feature2 


      Step 6: Delete feature2 branch.

      • ⋯ > Branch > Delete branch > Select feature2 

      • git branch will confirm that we now only have one branch, main.

      • Enter git log -3 to see the last 3 commits. And you can see the feature2 commit is included.



      Should you use Git Commands or VS Code Source Control

      • Whether you use Git commands or VS Code for executing git commands is a matter of preference. Commands that output to the terminal like status, diff, log, show are only available in the Terminal so you need to use the terminal at least part of the time.
      • If you prefer using the command line in general then use the Git commands. 
      • If you prefer GUIs in general then use VS Code Source Control.
      • If you don't have a preference or are unsure, I recommend using the GUI so you have fewer commands that you have to memorize. But still go through the Git commands in this tutorial series so you have some experience with them.

      Open CheatSheet Back To List Next Tutorial