All topics

Git

39 questions, 36 with answers.

  1. What is Git?

    Most widely used modern version control system in the world today. It is used to gather code contributions from multiple users in a single place (repository). Provides full history, workflow and allows for rollback of code and patching.

    From Tech Vault (Apache 2.0)

  2. Difference between Git and SVN?

    SVN and Git are both powerful version control systems that each use a different approach to managing and merging code changes. Git uses a distributed model, whereas SVN uses a centralized model.

    SVN’s centralized repository model makes it easier to manage contributions and contributors. Git does not support codebase access restrictions — a contributor who has access to the repository has access to the entire repository. SVN, by contrast, provides granular control, allowing for limits on particular contributors down to the directory, and file levels.

    The ability to work locally and offline is one major advantage to Git. SVN requires contributors to be connected to the main repository server, which essentially eliminates working offline.

    Git also outperforms SVN when it comes to merging and conflict resolution. Git has been designed for an open-source setting where numerous contributors may be working on the same parts of a codebase. To allow for this type of collaboration, Git has built up a robust system for resolving merge conflicts that makes the process smoother, and more manageable.

    From Tech Vault (Apache 2.0)

  3. What is the basic Git workflow?

    Working directory > staging area > local repo > remote repo git add git commit git push

    From Tech Vault (Apache 2.0)

  4. Difference between git pull and Git fetch

    The key difference between git fetch and pull is that git pull copies changes from a remote repository directly into your working directory, while git fetch does not. The git fetch command only copies changes into your local Git repo. The git pull command does both.

    Benefit of git pull: The local Git repo is now in sync with the remote repo. The local filesystem has the latest, most up to date files.

    Benefit of git fetch: If you are actively working on files tracked by Git, but you still want to update your local repository with the latest changes from a remote repository, use the git fetch command.

    From Tech Vault (Apache 2.0)

  5. What is git cherry-pick?

    git cherry-pick is a Git command used to apply a specific commit (or a range of commits) from one branch to another. It allows you to select and "cherry-pick" individual commits from one branch's history and apply them onto another branch. This can be useful when you want to bring specific changes or fixes from one branch into another without merging the entire branch.

    The basic syntax of git cherry-pick is as follows:

    
    git cherry-pick <commit-hash>
    <commit-hash> is the unique identifier (SHA-1 hash) of the commit you want to apply.
    

    From Tech Vault (Apache 2.0)

  6. What is the HEAD in Git?

    In Git, HEAD is a pointer to the latest commit in the currently checked-out branch. It represents the current state of the branch and is used for navigating the commit history and tracking changes. When in a "detached" state, HEAD points directly to a specific commit.

    From Tech Vault (Apache 2.0)

  7. When do I use Git stash?

    You use git stash in Git when you need to temporarily save changes in your working directory without committing them. This is typically done in scenarios where you want to switch to a different branch, pull changes from a remote repository, or perform some other operation that requires a clean working directory

    Here are common situations when you should use git stash:

    Switching Branches: When you're working on one branch and need to switch to another, but you have uncommitted changes in your working directory. Using git stash allows you to save those changes, switch branches, and then later apply the changes to the new branch.

    git stash        # Save changes
    git checkout another-branch   # Switch branches
    git stash apply  # Apply saved changes to the new branch
    

    Pulling or Fetching Changes: Before pulling or fetching changes from a remote repository, you can stash your local changes to ensure a clean working directory. This helps prevent conflicts that might arise when Git tries to merge the incoming changes with your local modifications.

    git stash        # Save changes
    git pull origin main   # Pull changes from the remote
    git stash apply  # Apply saved changes to your working directory
    

    Temporary Changes: If you're working on a feature but need to make a quick fix or test something unrelated, you can stash your current changes before making the temporary changes. Afterward, you can apply the stashed changes back.

    git stash        # Save feature changes
    # Make and test quick fix or unrelated changes
    git stash apply  # Apply saved feature changes back
    

    Resolving Conflicts: When resolving merge or rebase conflicts, git stash can help. You can stash your changes, then perform the merge or rebase. After resolving conflicts, you can apply your stashed changes again.

    git stash        # Save changes
    # Resolve conflicts during merge or rebase
    git stash apply  # Apply saved changes after conflicts are resolved
    

    From Tech Vault (Apache 2.0)

  8. What does git reset do?

    git reset is a Git command used to move the HEAD and optionally the index (staging area) to a specified commit. It has different modes, including soft (moves HEAD only), mixed (default, moves HEAD and unstages changes), and hard (moves HEAD, unstages changes, and discards changes in the working directory). You can use it to unstage changes, move the branch pointer, undo commits, and amend the last commit. Use it carefully as it can affect commit history.

    Here are the primary functions of git reset:

    • Unstaging Changes
    • Moving the HEAD
    • Undoing Commits: git reset
    • Mixed-Mode for Amend

    From Tech Vault (Apache 2.0)

  9. What is Git fork? What is difference between git fork, clone and branch?
    • Git Fork: Creating a copy of a repository on a Git hosting platform, often for collaborative contributions.
    • Git Clone: Creating a local copy of a Git repository from a remote, enabling local development.
    • Git Branch: Creating separate lines of development within a repository, typically for features or bug fixes.

    From Tech Vault (Apache 2.0)

  10. What is difference between git stash pop and git stash apply?
    • git stash pop applies and removes the most recent stash.
    • git stash apply applies the most recent stash but leaves it in the stash list for future use or reference.git stash pop applies and removes the most recent stash.

    From Tech Vault (Apache 2.0)

  11. I need to update my local repos, what commands do I use?
    • Use git fetch to retrieve remote changes.
    • Choose to merge with git merge or rebase with git rebase.
    • Resolve conflicts if any.
    • Optionally, push local changes with git push to update the remote repository.

    From Tech Vault (Apache 2.0)

  12. How can I amend an older commit?
    • Use git rebase -i <commit>~1 to start an interactive rebase.
    • Change "pick" to "edit" for the commit you want to amend.
    • Make your changes and stage them with git add .
    • Use git commit --amend to update the commit.
    • Continue the rebase with git rebase --continue

    From Tech Vault (Apache 2.0)

  13. When do you use git rebase instead of git merge?
    • Use git rebase instead of git merge when you want to create a cleaner, linear commit history, squash commits, or integrate changes from one branch into another. Use git merge when preserving the branch's history is more important, especially in collaborative scenarios.

    From Tech Vault (Apache 2.0)

  14. Do you know how to undo a git rebase?
    • Use git reflog to find the commit hash before the rebase.
    • Run git reset --hard <commit-hash> to reset your branch to that commit.
    • Optionally, force push to update the remote branch if necessary.

    From Tech Vault (Apache 2.0)

  15. How do you bring down updates from main branch if your local branch becomes stale?
    • Use git checkout <branch-name> to switch to your local branch.
    • Run git fetch to get the latest changes from the remote repository.
    • Choose either git merge main or git rebase main to integrate the updates (pick one based on your workflow).
    • Resolve any conflicts if they arise during the merge or rebase.
    • Test your branch thoroughly to ensure it works with the latest changes.
    • Commit and push your changes if necessary (git commit and git push origin <branch-name>).

    From Tech Vault (Apache 2.0)

  16. Explain some basic git commands.Basic
    • git init - create a new local repository
    • git commit -m "message" - commit changes to head
    • git status - list the files you've added with git add and also commit any files you've changed since then
    • git push origin master - send changes to the master branch of your remote repository

    From Test your Sysadmin Skills (MIT)

  17. How to git clone including submodules?Intermediate

    For example:

    # With -j8 - performance optimization
    git clone --recurse-submodules -j8 git://github.com/foo/bar.git
    # For already cloned repos or older Git versions
    git clone git://github.com/foo/bar.git
    cd bar
    git submodule update --init --recursive
    

    From Test your Sysadmin Skills (MIT)

  18. What is the difference between merge and rebase?
    • Both commits D and E are still here, but we create merge commit M that inherits changes from both D and E. However, this creates diamond shape, which many people find very confusing.
    • We create commit R, which actual file content is identical to that of merge commit M above. But, we get rid of commit E, like it never existed (denoted by dots - vanishing line). Because of this obliteration, E should be local to developer Ed and should have never been pushed to any other repository. Links
    • https://stackoverflow.com/questions/16666089/whats-the-difference-between-git-merge-and-git-rebase

    From Java interview (MIT)

  19. What is git reset?

    git-reset - Reset current HEAD to the specified state Links

    • https://git-scm.com/docs/git-reset
    • https://www.atlassian.com/git/tutorials/undoing-changes/git-reset

    From Java interview (MIT)

  20. What is the difference between soft reset and hard reset?
    • soft: uncommit changes, changes are left staged (index).
    • mixed (default): uncommit + unstage changes, changes are left in working tree.
    • hard: uncommit + unstage + delete changes, nothing left. Links
    • https://stackoverflow.com/questions/3528245/whats-the-difference-between-git-reset-mixed-soft-and-hard

    From Java interview (MIT)

  21. What is the difference between 'git pull' and 'git fetch'?

    In the simplest terms, git pull does a git fetch followed by a git merge.

    git fetch updates your remote-tracking branches under refs/remotes/<remote>/. This operation is safe to run at any time since it never changes any of your local branches under refs/heads.

    git pull brings a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.

    From the Git documentation for git pull:

    git pull runs git fetch with the given parameters and then depending on configuration options or command line flags, will call either git rebase or git merge to reconcile diverging branches.

    From Stack Overflow: asked by Pablo Fernandez, answered by Greg Hewgill (CC BY-SA 4.0)

  22. Difference between "git add -A" and "git add ."

    This answer only applies to Git version 1.x. For Git version 2.x, see other answers.

    Summary:

    • 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

    Detail:

    git add -A is equivalent to git add .; git add -u.

    The important point about git add . is that it looks at the working tree and adds all those paths to the staged changes if they are either changed or are new and not ignored, it does not stage any 'rm' actions.

    git add -u looks at all the already tracked files and stages the changes to those files if they are different or if they have been removed. It does not add any new files, it only stages changes to already tracked files.

    git add -A is a handy shortcut for doing both of those.

    You can test the differences out with something like this (note that for Git version 2.x your output for git add . git status will be different):

    git init
    echo Change me > change-me
    echo Delete me > delete-me
    git add change-me delete-me
    git commit -m initial
    echo OK >> change-me
    rm delete-me
    echo Add me > add-me
    git status
    # Changed but not updated:
    #   modified:   change-me
    #   deleted:    delete-me
    # Untracked files:
    #   add-me
    git add .
    git status
    # Changes to be committed:
    #   new file:   add-me
    #   modified:   change-me
    # Changed but not updated:
    #   deleted:    delete-me
    git reset
    git add -u
    git status
    # Changes to be committed:
    #   modified:   change-me
    #   deleted:    delete-me
    # Untracked files:
    #   add-me
    git reset
    git add -A
    git status
    # Changes to be committed:
    #   new file:   add-me
    #   modified:   change-me
    #   deleted:    delete-me
    

    From Stack Overflow: asked by cmcginty, answered by Lara Bailey (CC BY-SA 4.0)

  23. What does cherry-picking a commit with Git mean?

    Cherry-picking in Git means choosing a commit from one branch and applying it to another.

    This contrasts with other ways such as merge and rebase which normally apply many commits to another branch.

    It's also possible to cherry-pick multiple commits but merge is the preferred way over cherry-picking.

    1. Make sure you are on the branch you want to apply the commit to.

      git switch master
      
    2. Execute the following:

      git cherry-pick <commit-hash>
      

    N.B.:

    1. If you cherry-pick from a public branch, you should consider using

      git cherry-pick -x <commit-hash>
      

      This will generate a standardized commit message. This way, you (and your co-workers) can still keep track of the origin of the commit and may avoid merge conflicts in the future.

    2. If you have notes attached to the commit they do not follow the cherry-pick. To bring them over as well, You have to use:

      git notes copy <from> <to>
      

    Additional links:

    From Stack Overflow: asked by Rahul, answered by Philip Fourie (CC BY-SA 4.0)

  24. How can I see the differences between two branches?

    Use git diff.

    git diff [<options>] <commit>..​<commit> [--] [<path>…​]
    

    <commit> is a branch name, a commit hash, or a shorthand symbolic reference.

    Examples:

    git diff abc123..def567

    git diff HEAD..origin/master

    That will produce the diff between the tips of the two branches. If you'd prefer to find the changes that occurred in the common ancestor since the branch was started off, you can use three dots instead of two:

    git diff <commit>...<commit>
    

    To check which files differ, not how the content differs, use --name-only:

    git diff --name-only <commit>..​<commit>
    

    Note that in the <commit>..<commit> (two dot) syntax, the dots are optional; the following is synonymous:

    git diff commit1 commit2
    

    From Stack Overflow: asked by isuruanu, answered by Lazy Badger (CC BY-SA 4.0)

  25. How do I undo the most recent local commits in Git?

    Undo a commit & redo

    $ git commit -m "Something terribly misguided" # (0: Your Accident)
    $ git reset HEAD~                              # (1)
    # === If you just want to undo the commit, stop here! ===
    [ edit files as necessary ]                    # (2)
    $ git add .                                    # (3)
    $ git commit -c ORIG_HEAD                      # (4)
    
    1. git reset is the command responsible for the undo. It will undo your last commit while leaving your working tree (the state of your files on disk) untouched. You'll need to add them again before you can commit them again.
    2. Make corrections to working tree files.
    3. git add anything that you want to include in your new commit.
    4. Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEAD; commit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the -C option.

    Alternatively, to edit the previous commit (or just its commit message), commit --amend will add changes within the current index to the previous commit.

    To remove (not revert) a commit that has been pushed to the server, rewriting history with git push origin main --force[-with-lease] is necessary. It's almost always a bad idea to use --force; prefer --force-with-lease instead, and as noted in the git manual:

    You should understand the implications of rewriting history if you amend a commit that has already been published.

    Further Reading

    You can use git reflog to determine the SHA-1 for the commit to which you wish to revert. Once you have this value, use the sequence of commands as explained above.

    HEAD~ is the same as HEAD~1. The article What is the HEAD in git? is helpful if you want to uncommit multiple commits.

    From Stack Overflow: asked by Hamza Yerlikaya, answered by Esko Luontola (CC BY-SA 4.0)

  26. How do I delete a Git branch locally and remotely?

    Executive Summary

    git push -d <remote_name> <branchname>   # Delete remote
    git branch -d <branchname>               # Delete local
    

    Note: In most cases, <remote_name> will be origin.

    Delete Local Branch

    To delete the local branch, use one of the following:

    git branch -d <branch_name>
    git branch -D <branch_name>
    
    • The -d option is an alias for --delete, which only deletes the branch if it has already been fully merged in its upstream branch.
    • The -D option is an alias for --delete --force, which deletes the branch "irrespective of its merged status." [Source: man git-branch]
    • As of Git v2.3, git branch -d (delete) learned to honor the -f (force) flag.
    • You will receive an error if you try to delete the currently selected branch.

    Delete Remote Branch

    As of Git v1.7.0, you can delete a remote branch using

    $ git push <remote_name> --delete <branch_name>
    

    which might be easier to remember than

    $ git push <remote_name> :<branch_name>
    

    which was added in Git v1.5.0 "to delete a remote branch or a tag."

    Starting with Git v2.8.0, you can also use git push with the -d option as an alias for --delete. Therefore, the version of Git you have installed will dictate whether you need to use the easier or harder syntax.

    Delete Remote Branch [Original Answer from 5-Jan-2010]

    From Chapter 3 of Pro Git by Scott Chacon:

    Deleting Remote Branches

    Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s main branch (or whatever branch your stable code-line is in). You can delete a remote branch using the rather obtuse syntax git push [remotename] :[branch]. If you want to delete your serverfix branch from the server, you run the following:

    $ git push origin :serverfix
    To git@github.com:schacon/simplegit.git
     - [deleted]         serverfix
    

    Boom. No more branches on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the git push [remotename] [localbranch]:[remotebranch] syntax that we went over a bit earlier. If you leave off the [localbranch] portion, then you’re basically saying, “Take nothing on my side and make it be [remotebranch].”

    I ran git push origin :bugfix, and it worked beautifully. Scott Chacon was right—I will want to dog-ear that page (or virtually dog ear-by answering this on Stack Overflow).

    Fetch changes

    Finally, execute the following on other machines to propagate changes:

    # Fetch changes from all remotes and locally delete 
    # remote deleted branches/tags etc
    # --prune will do the job :-;
    git fetch --all --prune
    

    From Stack Overflow: asked by Matthew Rankin, answered by Matthew Rankin (CC BY-SA 4.0)

  27. How can I rename a local Git branch?

    To rename the current branch:

    git branch -m <newname>
    

    To rename a branch while pointed to any branch:

    git branch -m <oldname> <newname>
    

    -m is short for --move.

    To push the local branch and reset the upstream branch:

    git push origin -u <newname>
    

    To delete the remote branch:

    git push origin --delete <oldname>
    

    To create a git rename alias:

    git config --global alias.rename 'branch -m'
    

    On Windows or another case-insensitive filesystem, use -M if there are only capitalization changes in the name. Otherwise, Git will throw a "branch already exists" error.

    git branch -M <newname>
    

    From Stack Overflow: asked by Forrest, answered by siride (CC BY-SA 4.0)

  28. How do I undo 'git add' before commit?

    To unstage a specific file

    git reset <file>
    

    That will remove the file from the current index (the "about to be committed" list) without changing anything else.

    To unstage all files from the current change set:

    git reset
    

    In old versions of Git, the above commands are equivalent to git reset HEAD <file> and git reset HEAD respectively, and will fail if HEAD is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called HEAD, which is a stupid thing that you shouldn't do). This was changed in Git 1.8.2, though, so in modern versions of Git you can use the commands above even prior to making your first commit:

    "git reset" (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).

    Documentation: git reset

    From Stack Overflow: asked by oz10, answered by genehack (CC BY-SA 4.0)

  29. How do I force "git pull" to overwrite local files?

    ⚠ Warning:

    Any uncommitted local change to tracked files will be lost, even if staged.

    But any local file that's not tracked by Git will not be affected.

    First, update all origin/<branch> refs to latest:

    git fetch --all
    

    Backup your current branch (e.g. main):

    git branch backup-main
    

    Jump to the latest commit on origin/main and checkout those files:

    git reset --hard origin/main
    

    Explanation:

    git fetch downloads the latest from remote without trying to merge or rebase anything.

    git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/main.

    Maintain current local commits

    [*]: It's worth noting that it is possible to maintain current local commits by creating a branch from main before resetting:

    git checkout main
    git branch new-branch-to-save-current-commits
    git fetch --all
    git reset --hard origin/main
    

    After this, all of the old commits will be kept in new-branch-to-save-current-commits.

    Uncommitted changes

    Uncommitted changes, even if staged (with git add), will be lost. Make sure to stash or commit anything you need. For example, run the following:

    git stash
    

    And later (after git reset), reapply these uncommitted changes:

    git stash pop
    

    Which may create merge conflicts.

    From Stack Overflow: asked by Jakub Troszok, answered by RNA (CC BY-SA 4.0)

  30. How can I check out a remote Git branch?

    The answer has been split depending on whether there is one remote repository configured or multiple. The reason for this is that for the single remote case, some of the commands can be simplified as there is less ambiguity.

    Updated for Git 2.23: For older versions, see the section at the end.

    With One Remote

    In both cases, start by fetching from the remote repository to make sure you have all the latest changes downloaded.

    $ git fetch
    

    This will fetch all of the remote branches for you. You can see the branches available for checkout with:

    $ git branch -v -a
    ...
    remotes/origin/test
    

    The branches that start with remotes/* can be thought of as read only copies of the remote branches. To work on a branch you need to create a local branch from it. This is done with the Git command switch (since Git 2.23) by giving it the name of the remote branch (minus the remote name):

    $ git switch test
    

    In this case Git is guessing (can be disabled with --no-guess) that you are trying to checkout and track the remote branch with the same name.

    With Multiple Remotes

    In the case where multiple remote repositories exist, the remote repository needs to be explicitly named.

    As before, start by fetching the latest remote changes:

    $ git fetch origin
    

    This will fetch all of the remote branches for you. You can see the branches available for checkout with:

    $ git branch -v -a
    

    With the remote branches in hand, you now need to check out the branch you are interested in with -c to create a new local branch:

    $ git switch -c test origin/test
    

    For more information about using git switch:

    $ man git-switch
    

    Prior to Git 2.23

    git switch was added in Git 2.23, prior to this git checkout was used to switch branches.

    To checkout out with only a single remote repository:

    git checkout test
    

    if there are multiple remote repositories configured then it becomes a bit longer

    git checkout -b test <name of remote>/test
    

    From Stack Overflow: asked by Juri Glass, answered by hallski (CC BY-SA 4.0)

After the last page: 3 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.