Precious Mae
Posted on August 27, 2024
Edited (11/04/2024): Included git switch
command.
One of the most important concepts you have to learn when starting out in coding, and one you’ll continue to use even as you become a professional, is Git and GitHub. With these two technologies, you’ll be able to streamline your coding workflow, collaborate seamlessly with teams, and contribute to open-source projects.
Note: This article is intended for ultimate beginners to begin using Git bash. Git has multiple GUI clients that could be used, including GitHub desktop, but we'll be using Git bash in this article.
Git vs GitHub
Contrary to most beginners’ belief, Git and GitHub are entirely different from one another. However, they are commonly used alongside one another.
Git is the most famous and widely used free and open-source version control system. It's used by most industry tech companies such as Google, Twitter, Microsoft, and many more. It was created by Linus Torvalds, the creator and lead developer of the Linux kernel, in 2005.
GitHub, on the other hand, is a repository hosting service. It is a place for developers to publish their code. When working on a team, you often need a remote place to put your code so others can view or access it, and even contribute to its development.
Your GitHub Account
To start, let's create your GitHub account first.
- Navigate to GitHub, and click on Sign up on the right of the header.
- Enter your email address, a password, and a username.
- GitHub will send a verification to code to your email address, access it and enter it when prompted.
Starting out with Git
As mentioned earlier, Git is a free and open-source version control system. Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.
Your First Repo:
- First, navigate to the Git downloads page.
- Download the latest 64-bit version of Git for Windows, and install it once it has finished downloading.
- Open Git Bash by navigating to the folder where you have installed the Git or just simply search in the Windows search bar for Git bash.
- Run the following command to Git bash:
git --version
. If Git was installed properly, it should show the version of Git you just installed. -
Now let's let Git know who we are and setup your username and email.
Run the following commands:git config --global user.name "yourusername" git config --global user.email "your@email.com"
Note: Use the same credentials you used with your GitHub account in the prior section.
Check if everything is configured correctly:
git config --global -l
-
Set up your default code editor. For this article, we'll be setting VSCode as our default:
git config --global core.editor "code --wait"
Remote repository
Now, let's create your first remote repository.
-
Create a folder using the command:
mkdir first-repo && cd first-repo && code .
Note:
mkdir
stands for make directory, it creates a folder with the name you specified, in this case, it is first-repo.cd
stands for change directory, it changes your current working directory.code .
opens your current directory in your chosen code editor. -
Initialize your first Git repository.
git init
-
Create your first file in the repository.
touch HelloWorld.c && code HelloWorld.c
Note:
touch
is a standard command used in the UNIX/Linux operating system which is used to create, change and modify the timestamps of a file, in this case we are using it to create theHelloWorld.c
file.code HelloWorld.c
is a VSCode command that opens the file specified,HelloWorld.c
in VSCode. -
Paste the following code to the file:
#include <stdio.h> int main(){ printf("Hello World!"); }
-
Save your changes and run this command in the terminal:
git add .
git add
tells Git to begin tracking the files specified. the.
adds all the files in the current directory you are in.Before changes are committed to the repository history, they live in the staging index and the working directory.
The contents of your project folder (the folders and files you find within it) are represented by the working directory. The staging index is when Git starts tracking and saving changes that occur in files. Files in the staging index are tracked by Git.
If you don't want to track all the files in your directory, you can manually list the files you wish to track, e.g.
git add Documentation/*.txt
, which adds content from all *.txt files under Documentation directory and its subdirectories, orgit add README.md HelloWorld.c
, which adds the README.md file and HelloWorld.c file.Files in your Git repository folder can be in one of 2 states:
- Tracked - files that Git knows about and are added to the repository.
- Untracked - files that are in your working directory, but not added to the repository.
Commits
-
Check if the status of your repo using:
git status
This will display your tracked and untracked files, the status of your branch (if it is ahead or behind), etc.
-
Since all your changes have been staged, you are ready to create your first commit.
git commit -m "chore: init"
Note:
git commit
is the command to create a commit.-m
is a subcommand used to specify a commit message, in this case it is the"chore: init"
. If you don't use the-m
subcommand to specify a message, Git will open your code editor to make you write a commit message.Commits act like snapshots of your repository at specific times. You should make new commits often, based around logical units of change in your code and repository. Commits include lots of metadata in addition to the contents and message, like the author, timestamp, and more.
Commits require a commit message. These messages are extremely important, as they become a descriptor for the change you are commiting. To know how to write proper commit messages, check out this link: Guide for conventional commits.
Branches
Let's say I want to create another version of my project without affecting the main one. We can use branches to do this. Git branches are like separate paths or versions of your project where you can work on different features or fixes without affecting the main project. For local repositories, the name of the main branch is called master
, while on GitHub it is main
.
-
Create a new branch:
git branch name
name
is the name of the new branch we want to create, you can use whatever name you want, but in this tutorial let's usename
. If Git finds a branch with a similar name, it will throw an error. -
Change from your current branch to your new branch.
git checkout name
You can actually combine the these two steps into one by using:
git checkout -b name
This will create a new branch named
name
and also change your current branch toname
.You can also use a
git switch
to create a new branch and switch to it.
git switch -c name
-
Check what current branch you are working on with
git branch
If you are working on the correct branch, paste the following code into your
HelloWorld.c
file.
#include <stdio.h> int main(){ char name[] = "Linus"; printf("Hello, %s!", name); }
Stage and commit your changes:
git add . git commit -m "feat: added a variable name to print"
-
Now checkout your main branch with:
git checkout master
If everything worked out, this branch should not include the changes you made in the
name
branch. -
Let's merge the two branches together. Before merging to master, make sure that everything works first to ensure that you don't break anything.
Assuming you are still in the
master
branch, run the command:git merge name
This command should merge your
name
branch into themaster
branch.
Local repository to Remote
Now, let's connect your local repository to GitHub.
Open GitHub and create a new repository. Add a repository name, in this case we'll use
first-repo
. Choose if you want to make this repository public or private, and if you want to initialize a README.md (but we'll skip this for now). Click on Create repository once you're done.-
After creating your repository, GitHub will redirect you to a quick setup page. Copy the https link provided.
-
On your
first-repo
directory, run the following commands:git remote add origin <link you copied>
Replace the text inside the <> with the link you copied, and remove the <>. To see the remote repositories associated with your local repository, run:
git remote -v
-
Rename your branch
git branch -M main
This command will rename your current branch to
main
. The-m
stands for 'move' or 'rename'. As mentioned earlier, local repositories use the namemaster
for their main branch, while GitHub usesmain
. -
Push all your local commits to GitHub.
git push -u origin main
git push
is a command used to upload your local branch's commits to your remote GitHub repository.-u
or--set-upstream
is used to set the upstream branch, connecting your local main branch to the remote repository's main branch. You can just usegit push
after setting this.origin
is the default name for the remote repository in Git.main
specifies the branch you want to push, in this case, themain
branch.This command should push all your local commits to your GitHub repository. Check your GitHub for the changes.
Pulling changes from remote to local
Now, let's say that you're working on a project with multiple people, and one of your team members just pushed a change to your main branch.
-
First, let's simulate how this work. Go to your GitHub repository and click on Add file and Create a new file. Name your file
README.md
, a README file contains information about your project.A README.md uses Markdown Language. You can refer to this link for its' syntax: Markdown Language Syntax. Paste the following contents to your file:
# My First Repo Local repository to remote.
You can preview its contents, by clicking on the Preview button next to the Edit. Once everything is ok, click on Commit changes. A pop-up will appear prompting a commit message. Click on Commit changes once you are done.
-
On Git bash, run the following command:
Since you already set the upstream branch earlier, you can just use
git pull
directly.git pull
This will pull all the changes from your remote repository to your local. Look at your explorer or use the command
ls
in your Git bash to list all your files and directories.README.md
should be listed.
Undoing changes
Let's say I want to undo my changes and go back to a certain version of my project. There are several ways to undo commits, like git revert
, git reset
, git checkout
etc.
See all your commits using the
git log --oneline
command. This will display all the commits with their hashes. Commit histories are long, so the--oneline
subcommand limits the information displayed to one line.-
Copy the hash of the commit you want to go to. In this case, I want to revert to the initial commit with the hash
a894e0f
. But first, let's visit that commit.git checkout a894e0f
Undoing a commit with git checkout
-
Checkout to the commit you want to go back to.
git checkout a894e0f
Using this command will remove you from your current branch, which means you won't be working on any branch.
-
From this state, we can run:
git checkout -b newbranch_nocommit
The repository is now in a timeline where the
a894e0f
commit no longer exists.
Undoing a commit with git revert
Git revert is used to record some new commits to reverse the effect of some earlier commits. Unlike git checkout
, it creates a history of its undo. This is the ideal 'undo' method for working with public shared repositories.
Let's say I want to go back to my past commit.
git revert HEAD
HEAD is your current branch, or active branch. Git can only checkout one branch at a time, and this is your HEAD branch. When you change branches using the checkout
command, this new branch now becomes your new HEAD. git revert HEAD
creates a new commit that undoes the changes made by the latest commit (the one pointed to by HEAD).
git revert HEAD~3
This will revert the changes specified by the fourth last commit in HEAD and create a new commit with the reverted changes.
git revert a894e0f --no-edit
git revert a894e0f
reverts to the commit with the specified hash. --no-edit
skips the commit message editor, resulting in getting the default revert message.
Reverting to a certain commit will sometimes result in merge conflicts, wherein your past commit will have conflicts with your current commit. To handle these errors, you can open the conflicted file and decide what changes you want to accept.
Once you resolved all conflicts, run git revert --continue
.
Undoing uncommited changes
In the case wherein you have only staged your files, but did not commit them yet, you can run:
git reset
git reset
should generally be considered a 'local' undo method. git reset a894e0f
can also be used, where a894e0f
is the commit hash of the commit you want to go back to, but doing this will rewrite your repository's history, so it is not recommended. A reset should be used when undoing changes to a private branch. This safely isolates the removal of commits from other branches that may be in use by other developers.
On the hand, when your changes are in the working directory, you can run:
git clean
This command removes untracked files from the working tree. The Working Tree is the area where you are currently working, or where your files live. It cleans it by recursively removing files that are not under version control, starting from the current directory.
From remote to local: Cloning
We created a repository by using git init
in the prior section, but there is another way to create a repository, and that is by first creating a remote repository and cloning it into your local machine. This is helpful when you want to work on a project that is owned by someone else.
-
Similar to when we created a remote repository earlier, go to your GitHub, and create a new repository. Name your repository as
second-repo
, and initialize a README.md. Write in your README.md:
# second-repo Remote to local.
Commit your changes.
Go to your repository's home page, and click on Code. Copy the HTTPS url.
-
In Git bash,
cd
to a directory you want to clone your repository into.
cd repo-test
-
Once you're in the directory you want, run the command:
git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
This will clone your remote repository to your local machine.
-
cd
into yoursecond-repo
and open your README.md file. Edit the contents of your file:
# second-repo Remote to local. This is an edit.
-
Save, stage, and commit your changes.
git add README.md git commit -m "docs: edited README.md"
-
You can directly push to your remote repository.
git push
Conclusion
Git hosts a lot of features and commands, and what I covered in this article will only scratch the surface, but hopefully it will help you get started in exploring Git and GitHub. To know more, you can refer to Git's Documentation.
After reading article, you can consult W3School's Git and GitHub Tutorial or GeeksforGeeks' Ultimate Guide to Git and GitHub to explore other features such as .gitignore
or pull requests.
Posted on August 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.