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)
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)
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)
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)
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)
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)
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 branchPulling 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 directoryTemporary 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 backResolving 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 resolvedFrom Tech Vault (Apache 2.0)
What does git reset do?
git resetis 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)
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)
What is difference between
git stash popandgit stash apply?git stash popapplies and removes the most recent stash.git stash applyapplies 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)
I need to update my local repos, what commands do I use?
- Use
git fetchto retrieve remote changes. - Choose to merge with
git mergeor rebase withgit rebase. - Resolve conflicts if any.
- Optionally, push local changes with git push to update the remote repository.
From Tech Vault (Apache 2.0)
- Use
How can I amend an older commit?
- Use
git rebase -i <commit>~1to 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 --amendto update the commit. - Continue the rebase with
git rebase --continue
From Tech Vault (Apache 2.0)
- Use
When do you use
git rebaseinstead ofgit merge?- Use
git rebaseinstead ofgit mergewhen you want to create a cleaner, linear commit history, squash commits, or integrate changes from one branch into another. Usegit mergewhen preserving the branch's history is more important, especially in collaborative scenarios.
From Tech Vault (Apache 2.0)
- Use
Do you know how to undo a git rebase?
- Use
git reflogto 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)
- Use
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 fetchto get the latest changes from the remote repository. - Choose either
git merge mainorgit rebase mainto 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 commitandgit push origin <branch-name>).
From Tech Vault (Apache 2.0)
- Use
Explain some basic
gitcommands.Basicgit init- create a new local repositorygit commit -m "message"- commit changes to headgit status- list the files you've added withgit addand also commit any files you've changed since thengit push origin master- send changes to the master branch of your remote repository
From Test your Sysadmin Skills (MIT)
How to
git cloneincluding submodules?IntermediateFor 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 --recursiveFrom Test your Sysadmin Skills (MIT)
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)
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)
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)
What is the difference between 'git pull' and 'git fetch'?
In the simplest terms,
git pulldoes agit fetchfollowed by agit merge.git fetchupdates your remote-tracking branches underrefs/remotes/<remote>/. This operation is safe to run at any time since it never changes any of your local branches underrefs/heads.git pullbrings 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 pullrunsgit fetchwith the given parameters and then depending on configuration options or command line flags, will call eithergit rebaseorgit mergeto reconcile diverging branches.From Stack Overflow: asked by Pablo Fernandez, answered by Greg Hewgill (CC BY-SA 4.0)
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 -Astages all changesgit add .stages new files and modifications, without deletions (on the current directory and its subdirectories).git add -ustages modifications and deletions, without new files
Detail:
git add -Ais equivalent togit 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 -ulooks 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 -Ais 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 statuswill 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-meFrom Stack Overflow: asked by cmcginty, answered by Lara Bailey (CC BY-SA 4.0)
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
mergeandrebasewhich normally apply many commits to another branch.It's also possible to cherry-pick multiple commits but
mergeis the preferred way over cherry-picking.Make sure you are on the branch you want to apply the commit to.
git switch masterExecute the following:
git cherry-pick <commit-hash>
N.B.:
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.
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)
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..def567git diff HEAD..origin/masterThat 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 commit2From Stack Overflow: asked by isuruanu, answered by Lazy Badger (CC BY-SA 4.0)
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)git resetis 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.- Make corrections to working tree files.
git addanything that you want to include in your new commit.- Commit the changes, reusing the old commit message.
resetcopied the old head to.git/ORIG_HEAD;commitwith-c ORIG_HEADwill 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-Coption.
Alternatively, to edit the previous commit (or just its commit message),
commit --amendwill 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-leaseinstead, 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 reflogto 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 asHEAD~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)
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 localNote: In most cases,
<remote_name>will beorigin.Delete Local Branch
To delete the local branch, use one of the following:
git branch -d <branch_name> git branch -D <branch_name>- The
-doption is an alias for--delete, which only deletes the branch if it has already been fully merged in its upstream branch. - The
-Doption 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 pushwith the-doption 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 yourserverfixbranch from the server, you run the following:$ git push origin :serverfix To git@github.com:schacon/simplegit.git - [deleted] serverfixBoom. 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 --pruneFrom Stack Overflow: asked by Matthew Rankin, answered by Matthew Rankin (CC BY-SA 4.0)
- The
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>-mis 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 renamealias:git config --global alias.rename 'branch -m'On Windows or another case-insensitive filesystem, use
-Mif 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)
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 resetIn old versions of Git, the above commands are equivalent to
git reset HEAD <file>andgit reset HEADrespectively, and will fail ifHEADis undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch calledHEAD, 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)
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 --allBackup your current branch (e.g.
main):git branch backup-mainJump to the latest commit on
origin/mainand checkout those files:git reset --hard origin/mainExplanation:
git fetchdownloads the latest from remote without trying to merge or rebase anything.git resetresets the master branch to what you just fetched. The--hardoption changes all the files in your working tree to match the files inorigin/main.Maintain current local commits
[*]: It's worth noting that it is possible to maintain current local commits by creating a branch from
mainbefore resetting:git checkout main git branch new-branch-to-save-current-commits git fetch --all git reset --hard origin/mainAfter 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 tostashor commit anything you need. For example, run the following:git stashAnd later (after
git reset), reapply these uncommitted changes:git stash popWhich may create merge conflicts.
From Stack Overflow: asked by Jakub Troszok, answered by RNA (CC BY-SA 4.0)
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 fetchThis will fetch all of the remote branches for you. You can see the branches available for checkout with:
$ git branch -v -a ... remotes/origin/testThe 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 commandswitch(since Git 2.23) by giving it the name of the remote branch (minus the remote name):$ git switch testIn 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 originThis will fetch all of the remote branches for you. You can see the branches available for checkout with:
$ git branch -v -aWith the remote branches in hand, you now need to check out the branch you are interested in with
-cto create a new local branch:$ git switch -c test origin/testFor more information about using
git switch:$ man git-switchPrior to Git 2.23
git switchwas added in Git 2.23, prior to thisgit checkoutwas used to switch branches.To checkout out with only a single remote repository:
git checkout testif there are multiple remote repositories configured then it becomes a bit longer
git checkout -b test <name of remote>/testFrom 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.
- Tech Vaultby moabukar and contributorsApache 2.017 questions
- Test your Sysadmin Skillsby trimstray and contributorsMIT, © 2017 trimstray2 questions
- Java interviewby Anton LiauchukMIT, © 2020 Anton Liauchuk4 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA16 questions