Here are all the Git commands I used last week, and what they do. (2022)

Here are all the Git commands I used last week, and what they do. (1)

by Sam Corcos

Here are all the Git commands I used last week, and what they do. (2)

Like most newbies, I started out searching StackOverflow for Git commands, then copy-pasting answers, without really understanding what they did.

Here are all the Git commands I used last week, and what they do. (3)

I remember thinking, “Wouldn’t it be nice if there were a list of the most common Git commands along with an explanation as to why they are useful?”

Well, here I am years later to compile such a list, and lay out some best practices that even intermediate-advanced developers should find useful.

To keep things practical, I’m basing this list off of the actual Git commands I used over the past week.

Almost every developer uses Git, and most likely GitHub. But the average developer probably only uses these three commands 99% of the time:

(Video) Top 10 Git Commands | Most Used Git Commands | Git Commands With Examples | Simplilearn

git add --allgit commit -am "<message>"git push origin master

That’s all well and good when you’re working on a one-person team, a hackathon, or a throw-away app, but when stability and maintenance start to become a priority, cleaning up commits, sticking to a branching strategy, and writing coherent commit messages becomes important.

I’ll start with the list of commonly used commands to make it easier for newbies to understand what is possible with Git, then move into the more advanced functionality and best practices.

Regularly used commands

To initialize Git in a repository (repo), you just need to type the following command. If you don’t initialize Git, you cannot run any other Git commands within that repo.

git init

If you’re using GitHub and you’re pushing code to a GitHub repo that’s stored online, you’re using a remote repo. The default name (also known as an alias) for that remote repo is origin. If you’ve copied a project from Github, it already has an origin. You can view that origin with the command git remote -v, which will list the URL of the remote repo.

If you initialized your own Git repo and want to associate it with a GitHub repo, you’ll have to create one on GitHub, copy the URL provided, and use the command git remote add origin <URL>, with the URL provided by GitHub replacing “<URL>”. From there, you can add, commit, and push to your remote repo.

The last one is used when you need to change the remote repository. Let’s say you copied a repo from someone else and want to change the remote repository from the original owner’s to your own GitHub account. Follow the same process as git remote add origin, except use set-url instead to change the remote repo.

git remote -vgit remote add origin <url>git remote set-url origin <url>

The most common way to copy a repo is to use git clone, followed by the URL of the repo.

Keep in mind that the remote repository will be linked to the account from which you cloned the repo. So if you cloned a repo that belongs to someone else, you will not be able to push to GitHub until you change the origin using the commands above.

(Video) 10 Must Know Git Commands That Almost Nobody Knows

git clone <url>

You’ll quickly find yourself using branches. If you don’t understand what branches are, there are other tutorials that are much more in-depth, and you should read those before proceeding (here’s one).

The command git branch lists all branches on your local machine. If you want to create a new branch, you can use git branch <name>, with <name> representing the name of the branch, such as “master”.

The git checkout <name> command switches to an existing branch. You can also use the git checkout -b <name> command to create a new branch and immediately switch to it. Most people use this instead of separate branch and checkout commands.

git branchgit branch <name>git checkout <name>git checkout -b <name>

If you’ve made a bunch of changes to a branch, let’s call it “develop”, and you want to merge that branch back into your master branch, you use the git merge <branch> command. You’ll want to checkout the master branch, then run git merge develop to merge develop into the master branch.

git merge <branch>

If you’re working with multiple people, you’ll find yourself in a position where a repo was updated on GitHub, but you don’t have the changes locally. If that’s the case, you can use git pull origin <branch> to pull the most recent changes from that remote branch.

git pull origin <branch>

If you’re curious to see what files have been changed and what’s being tracked, you can use git status. If you want to see how much each file has been changed, you can use git diff to see the number of lines changed in each file.

git statusgit diff --stat

Advanced commands and best practices

Soon you reach a point where you want your commits to look nice and stay consistent. You might also have to fiddle around with your commit history to make your commits easier to comprehend or to revert an accidental breaking change.

The git log command lets you see the commit history. You’ll want to use this to see the history of your commits.

(Video) Git commands with examples - How to use git

Your commits will come with messages and a hash, which is random series of numbers and letters. An example hash might look like this: c3d882aa1aa4e3d5f18b3890132670fbeac912f7

git log

Let’s say you pushed something that broke your app. Rather than fix it and push something new, you’d rather just go back one commit and try again.

If you want to go back in time and checkout your app from a previous commit, you can do this directly by using the hash as the branch name. This will detach your app from the current version (because you’re editing a historical record, rather than the current version).

git checkout c3d88eaa1aa4e4d5f

Then, if you make changes from that historical branch and you want to push again, you’d have to do a force push.

Caution: Force pushing is dangerous and should only be done if you absolutely must. It will overwrite the history of your app and you will lose whatever came after.

git push -f origin master

Other times it’s just not practical to keep everything in one commit. Perhaps you want to save your progress before trying something potentially risky, or perhaps you made a mistake and want to spare yourself the embarrassment of having an error in your version history. For that, we have git rebase.

Let’s say you have 4 commits in your local history (not pushed to GitHub) in which you’ve gone back and forth. Your commits look sloppy and indecisive. You can use rebase to combine all of those commits into a single, concise commit.

git rebase -i HEAD~4

The above command will open up your computer’s default editor (which is Vim unless you’ve set it to something else), with several options for how you can change your commits. It will look something like the code below:

(Video) Daily git commands for a professional programmer pt1

pick 130deo9 oldest commit messagepick 4209fei second oldest commit messagepick 4390gne third oldest commit messagepick bmo0dne newest commit message

In order to combine these, we need to change the “pick” option to “fixup” (as the documentation below the code says) to meld the commits and discard the commit messages. Note that in vim, you need to press “a” or “i” to be able to edit the text, and to save and exit, you need to type the escape key followed by “shift + z + z”. Don’t ask me why, it just is.

pick 130deo9 oldest commit messagefixup 4209fei second oldest commit messagefixup 4390gne third oldest commit messagefixup bmo0dne newest commit message

This will merge all of your commits into the commit with the message “oldest commit message”.

The next step is to rename your commit message. This is entirely a matter of opinion, but so long as you follow a consistent pattern, anything you do is fine. I recommend using the commit guidelines put out by Google for Angular.js.

In order to change the commit message, use the amend flag.

git commit --amend

This will also open vim, and the text editing and saving rules are the same as above. To give an example of a good commit message, here’s one following the rules from the guideline:

feat: add stripe checkout button to payments page- add stripe checkout button- write tests for checkout

One advantage to keeping with the types listed in the guideline is that it makes writing change logs easier. You can also include information in the footer (again, specified in the guideline) that references issues.

Note: you should avoid rebasing and squashing your commits if you are collaborating on a project, and have code pushed to GitHub. If you start changing version history under people’s noses, you could end up making everyone’s lives more difficult with bugs that are difficult to track.

There are an almost endless number of possible commands with Git, but these commands are probably the only ones you’ll need to know for your first few years of programming.

(Video) SAS Tutorial | How to use Git with SAS

Sam Corcos is the lead developer and co-founder of Sightline Maps, the most intuitive platform for 3D printing topographical maps, as well as LearnPhoenix.io, an intermediate-advanced tutorial site for building scalable production apps with Phoenix and React.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

FAQs

What are the git commands you have used? ›

Git commands
  • git add. Moves changes from the working directory to the staging area. ...
  • git branch. This command is your general-purpose branch administration tool. ...
  • git checkout. ...
  • git clean. ...
  • git clone. ...
  • git commit. ...
  • git commit --amend. ...
  • git config.

How do I see previous git commands? ›

On GitHub.com, you can access your project history by selecting the commit button from the code tab on your project. Locally, you can use git log . The git log command enables you to display a list of all of the commits on your current branch. By default, the git log command presents a lot of information all at once.

How do I see my git history? ›

Git file History provides information about the commit history associated with a file. To use it: Go to your project's Repository > Files. In the upper right corner, select History.

What is git and its command? ›

Git is a distributed version-control system for tracking changes in any set of files, originally designed for coordinating work among programmers cooperating on source code during software development. Its goals include speed, data integrity, and support for distributed, non-linear workflows (Source: Wikipedia).

What type of command is git? ›

Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals.

How do you check what changes were made in git? ›

Viewing Your Staged and Unstaged Changes
  1. To see what you've changed but not yet staged, type git diff with no other arguments: ...
  2. If you want to see what you've staged that will go into your next commit, you can use git diff --staged .

How can I see my last commits? ›

Viewing a list of the latest commits. If you want to see what's happened recently in your project, you can use git log . This command will output a list of the latest commits in chronological order, with the latest commit first.

How do I see my git history in GitHub? ›

On GitHub, you can see the commit history of a repository by: Navigating directly to the commits page of a repository. Clicking on a file, then clicking History, to get to the commit history for a specific file.

How do I commit in git? ›

To add a Git commit message to your commit, you will use the git commit command followed by the -m flag and then your message in quotes. Adding a Git commit message should look something like this: git commit -m “Add an anchor for the trial end sectionnn.”

What is a git log? ›

Git log is a utility tool to review and read a history of everything that happens to a repository. Multiple options can be used with a git log to make history more specific. Generally, the git log is a record of commits.

How do I revert a git commit? ›

The revert command

You can find the name of the commit you want to revert using git log . The first commit that's described there is the last commit created. Then you can copy from there the alphanumerical name and use that in the revert command. In this image, each circe represents a commit.

Where do I write git commands? ›

Press 'Start' button in Windows, type 'cmd' in the search field on the bottom of menu. There you have the command line console. Try to type git --version , if show something like 'git version 1.8. 0.2', you're ready to input all the commands here.

What is git example? ›

What is Git? Git is a DevOps tool used for source code management. It is a free and open-source version control system used to handle small to very large projects efficiently. Git is used to tracking changes in the source code, enabling multiple developers to work together on non-linear development.

What is the git command to create a branch? ›

New Branches

The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.

What is the first command in git? ›

The git init command creates a new Git repository. It can be used to convert an existing, unversioned project to a Git repository or initialize a new, empty repository. Most other Git commands are not available outside of an initialized repository, so this is usually the first command you'll run in a new project.

What are the commands of git to push the code? ›

Different Commands in Git
  • Git config.
  • Git init.
  • Git add.
  • Git diff.
  • Git commit.
  • Git reset.
  • Git status.
  • Git merge.
25 Jul 2022

Which command is used to check the list of branches? ›

To see local branches, use the git branch command. The git branch command lets you see a list of all the branches stored in your local version of a repository.

What is git merge command? ›

The git merge command lets you take the independent lines of development created by git branch and integrate them into a single branch. Note that all of the commands presented below merge into the current branch.

What is origin in git? ›

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier. Note that origin is by no means a "magical" name, but just a standard convention.

How can I tell which files were changed in a commit? ›

To find out which files changed in a given commit, use the git log --raw command.

How do I see all files committed in git? ›

In Git, we can use git show commit_id --name-only to list all the committed files that are going to push to the remote repository.

How do I see files as committed in git? ›

When viewing a list of commits, there are various commands depending on how much info you want to see.
  1. To see a simplified list of commits, run this command: git log --oneline.
  2. To see a list of commits with more detail (such who made the commit and when), run this command: git log.

How do I get a list of commits? ›

The most basic and powerful tool to do this is the git log command. By default, with no arguments, git log lists the commits made in that repository in reverse chronological order; that is, the most recent commits show up first.

How can you fix a broken commit? ›

To fix a broken commit or to change the last commit, the most convenient method is to use the command “git commit -amend'. It allows you to combine staged changes with the previous commit as an alternative for creating an entirely new commit. This replaces the most recent commit with the amended commit.

How do you pull a commit? ›

To pull up a list of your commits and their associated hashes, you can run the git log command. To checkout a previous commit, you will use the Git checkout command followed by the commit hash you retrieved from your Git log.

How can I see commits in GitHub? ›

You can see details about any commit in GitHub Desktop, including a diff of the changes the commit introduced.
...
  1. Click History.
  2. On the History tab, click the commit you'd like to review.
  3. If there are multiple files in the commit, click on an individual file to see the changes made to that file in that commit.

What is the git command to view all the remote branches? ›

Command #1: git branch -r

This Git command will show you remote branches. The -r flag here is short for --remotes . This is the command I use personally.

How do I push to a branch? ›

To push the branch or you can say to push the changes in the branch to the Github repo you have to run this command “git push origin <the branch name>” in our case the branch name is “main”. After pushing the changes the repo will look like and this is how you can push a branch to a remotely hosted GitHub repository.

How do I merge two branches? ›

To do a merge (locally), git checkout the branch you want to merge INTO. Then type git merge <branch> where <branch> is the branch you want to merge FROM. Because the history of master and the history of make_function share common ancestors and don't have any divergence descendents, we get a "fast-forward" merge.

How do I commit a single file in git? ›

Try git commit -m 'my notes' path/to/my/file. ext , or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.

What is a git commit hash? ›

The commit hash is an SHA-1 hash made up of a few properties from the commit itself. As mentioned above, it is a lot more complex than this post can go into, but understanding the fundamentals is a great first step. The git hash is made up of the following: The commit message. The file changes.

What is git clone? ›

git clone is primarily used to point to an existing repo and make a clone or copy of that repo at in a new directory, at another location. The original repository can be located on the local filesystem or on remote machine accessible supported protocols. The git clone command copies an existing Git repository.

How do I edit a tag in git? ›

gistfile1.txt
  1. Create a branch with the tag. git branch {tagname}-branch {tagname} ...
  2. Include the fix manually if it's just a change .... git add . ...
  3. Delete and recreate the tag locally. git tag -d {tagname} ...
  4. Delete and recreate the tag remotely. ...
  5. Update local repository with the updated tag (suggestion by @wyattis)

How do I revert my last commit remote? ›

To undo the last commit from a remote git repository, you can use the git reset command. command. This will undo the last commit locally. command to force push the local commit which was reverted to the remote git repository.

How do I revert a git commit after push? ›

Scenario 4: Reverting a commit that has been pushed to the remote
  1. Go to the Git history.
  2. Right click on the commit you want to revert.
  3. Select revert commit.
  4. Make sure commit the changes is checked.
  5. Click revert.
7 Dec 2018

How do I remove untracked files in git? ›

Remove untracked files and folders
  1. To remove untracked files inside a subfolder use: git clean -f folderpath.
  2. The untracked folders will now be deleted. If you want to delete untracked folders too, you can use the -d flag: git clean -fd.
  3. To remove ignore files, use the -x flag: git clean -fx.

What is the first command in git? ›

The git init command creates a new Git repository. It can be used to convert an existing, unversioned project to a Git repository or initialize a new, empty repository. Most other Git commands are not available outside of an initialized repository, so this is usually the first command you'll run in a new project.

Where do I write git commands? ›

Press 'Start' button in Windows, type 'cmd' in the search field on the bottom of menu. There you have the command line console. Try to type git --version , if show something like 'git version 1.8. 0.2', you're ready to input all the commands here.

What are the commands in git bash? ›

A LIST OF GIT BASH COMMANDS:
  • git config --global user.name “[name]” This command sets username, which aids in reviewing by whom the changes were made.
  • git config --global user.email “[email address]” ...
  • git config --global color.ui auto. ...
  • git init. ...
  • git init [repository name] ...
  • git clone [url] ...
  • git add [file] ...
  • git add *
30 Mar 2021

What is git example? ›

What is Git? Git is a DevOps tool used for source code management. It is a free and open-source version control system used to handle small to very large projects efficiently. Git is used to tracking changes in the source code, enabling multiple developers to work together on non-linear development.

What is git Basics? ›

Git basics

Git is a free and open-source version control system, originally created by Linus Torvalds in 2005. Unlike older centralized version control systems such as SVN and CVS, Git is distributed: every developer has the full history of their code repository locally.

How do I commit in git? ›

To add a Git commit message to your commit, you will use the git commit command followed by the -m flag and then your message in quotes. Adding a Git commit message should look something like this: git commit -m “Add an anchor for the trial end sectionnn.”

How do I start a git repository? ›

Start a new git repository
  1. Create a directory to contain the project.
  2. Go into the new directory.
  3. Type git init .
  4. Write some code.
  5. Type git add to add the files (see the typical use page).
  6. Type git commit .

How do I push a git command? ›

Using Command line to PUSH to GitHub
  1. Creating a new repository. ...
  2. Open your Git Bash. ...
  3. Create your local project in your desktop directed towards a current working directory. ...
  4. Add the file to the new local repository. ...
  5. Add the URL copied, which is your remote repository to where your local content from your repository is pushed.

How do I setup git? ›

Setup Git and GitHub
  1. Go to GitHub.com and login.
  2. Click the green “New Repository” button. Repository name: myrepo. Public. Check Initialize this repository with a README. Click the green “Create repository” button.
  3. Copy the HTTPS clone URL to your clipboard via the green “Clone or Download” button.
7 Jul 2022

How do I commit and push in git Bash? ›

Makefile git add commit push github All in One command
  1. Open the terminal. Change the current working directory to your local repository. ...
  2. Commit the file that you've staged in your local repository. $ git commit -m "Add existing file"
  3. Push the changes in your local repository to GitHub. $ git push origin branch-name.

Which command is used to check the list of branches? ›

To see local branches, use the git branch command. The git branch command lets you see a list of all the branches stored in your local version of a repository.

What is git merge command? ›

The git merge command lets you take the independent lines of development created by git branch and integrate them into a single branch. Note that all of the commands presented below merge into the current branch.

Why is it called git? ›

Git, as a word, is an alternation of the word get, which itself was shortened from beget. The implicit reference is to illegitimate offspring, and the term is roughly synonymous with twit, dolt, moron or idiot.

What is origin in git? ›

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier. Note that origin is by no means a "magical" name, but just a standard convention.

How do I resolve merge conflicts in git? ›

How to Resolve Merge Conflicts in Git?
  1. The easiest way to resolve a conflicted file is to open it and make any necessary changes.
  2. After editing the file, we can use the git add a command to stage the new merged content.
  3. The final step is to create a new commit with the help of the git commit command.
5 Aug 2022

Videos

1. Git Pull Request | Git Pull Request Tutorial | Git Commands |Git Tutorial For Beginners |Simplilearn
(Simplilearn)
2. How to use Terragrunt Run All to Keep your Terraform code DRY
(env0)
3. Git Tutorial 4: Basic Commands: add, commit, push
(codebasics)
4. Git Tutorial for Beginners: Learn Git in 1 Hour
(Programming with Mosh)
5. Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git
(freeCodeCamp.org)
6. Learn Git In 15 Minutes
(Colt Steele)

Top Articles

Latest Posts

Article information

Author: The Hon. Margery Christiansen

Last Updated: 08/08/2022

Views: 5763

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.