gitlab-org--gitlab-foss/doc/topics/git/useful_git_commands.md

3.5 KiB

type
reference

Useful Git commands

Here are some useful Git commands collected by the GitLab support team. You may not need to use often, but they can can come in handy when needed.

Remotes

Add another URL to a remote, so both remotes get updated on each push

git remote set-url --add <remote_name> <remote_url>

Staging and reverting changes

Remove last commit and leave the changes in unstaged

git reset --soft HEAD^

Unstage a certain number of commits from HEAD

To unstage 3 commits, for example, run:

git reset HEAD^3

Unstage changes to a certain file from HEAD

git reset <filename>

Revert a file to HEAD state and remove changes

There are two options to revert changes to a file:

  • git checkout <filename>
  • git reset --hard <filename>

Undo a previous commit by creating a new replacement commit

git revert <commit-sha>

Create a new message for last commit

git commit --amend

Add a file to the last commit

git add <filename>
git commit --amend

Append --no-edit to the commit command if you do not want to edit the commit message.

Stashing

Stash changes

git stash save

The default behavor of stash is to save, so you can also use just:

git stash

Unstash your changes

git stash apply

Discard your stashed changes

git stash drop

Apply and drop your stashed changes

git stash pop

Refs and Log

Use reflog to show the log of reference changes to HEAD

git reflog

Check the Git history of a file

The basic command to check the Git history of a file:

git log <file>

If you get this error message:

fatal: ambiguous argument <file_name>: unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:

Use this to check the Git history of the file:

git log -- <file>

Find the tags that contain a particular SHA

git tag --contains <sha>

Check the content of each change to a file

gitk <file>

Check the content of each change to a file, follows it past file renames

gitk --follow <file>

Debugging

Use a custom SSH key for a Git command

GIT_SSH_COMMAND="ssh -i ~/.ssh/gitlabadmin" git <command>

Debug cloning

With SSH:

GIT_SSH_COMMAND="ssh -vvv" git clone <git@url>

With HTTPS:

GIT_TRACE_PACKET=1 GIT_TRACE=2 GIT_CURL_VERBOSE=1 git clone <url>

Rebasing

Rebase your branch onto master

The -i flag stands for 'interactive':

git rebase -i master

Continue the rebase if paused

git rebase --continue

Use git rerere

To reuse recorded solutions to the same problems when repeated:

git rerere

To enable rerere functionality:

git config --global rerere.enabled true