Git commands cheat sheet
Initial setup
-
git config --global user.name "Israel Israeli"Set the name that appears as the author of every new commit on the computer. Run this command once after you install Git.
-
git config --global user.email "israel@example.com"Set the email address recorded in every new commit. Git hosting services use this address to link the commits to your user account.
-
git config --global init.defaultBranch mainSet the main branch of every new repository to be named main.
-
git config --global core.editor "nano"Set the editor that opens for writing a commit message and for interactive operations. You can specify any installed editor, for example vim or "code --wait".
-
git config --global alias.st statusCreate an alias named st, so the git st command runs git status.
-
git config --global alias.lg "log --oneline --graph --all"Create an alias named lg that shows the history of all branches as a compact graph.
-
git config --global pull.rebase falseMake git pull integrate the changes from the remote repository with a merge. With the value true, the changes are integrated with a rebase.
-
git config --global push.autoSetupRemote trueMake git push create a branch with the same name in the remote repository the first time you push a new branch, and set up tracking for it automatically, without the -u option.
-
git config --global core.autocrlf inputMake Git convert Windows line endings (CRLF) to Linux line endings (LF) when files are added to the repository, without converting them back. On Windows computers, the value true is commonly used.
-
git config --list --show-originShow all the active settings and the file each setting was loaded from.
Creating and cloning
-
git initTurn the current directory into a new Git repository and create the hidden .git directory in it.
-
git clone https://example.com/user/site.gitDownload a full copy of a remote repository, including its entire history, into a new directory named site.
-
git clone git@example.com:user/site.gitClone a repository over SSH. The connection is authenticated with an SSH key, without typing a password.
-
git clone --depth 1 https://example.com/user/site.gitDownload only the latest commit, without the full history. A shallow clone like this is faster and takes up less space, so it suits installing or building a project.
-
git clone --branch dev --single-branch https://example.com/user/site.gitClone only one branch, in this case dev, without the other branches of the repository.
Changes and commits
-
git statusShow the current branch, the modified files, the files staged for the next commit, and the new untracked files.
-
git status -sShow the status of the files in a short format, one line per file. The first character on each line marks a staged change, and the second character marks a change that is not staged yet.
-
git add index.phpAdd the changes in the file to the staging area, so they are included in the next commit.
-
git add .Add to the staging area all the changes in the current directory and its subdirectories, including new files and deleted files.
-
git add -pShow each change (hunk) separately and choose which ones to add to the staging area. The answer y adds the hunk, n skips it, and q ends the selection.
-
git commit -m "Fix login form validation"Save the staged changes as a new commit with a short message that describes the change.
-
git commit -am "Update footer text"Stage and commit, in one step, changes and deletions in files that are already tracked. New files are not included, so add them first with git add.
-
git commit --amend -m "New message"Replace the last commit with a new commit, with the new message and with any changes you have staged. Caution: do not amend a commit that has already been pushed to a shared repository.
-
git commit --amend --no-editAdd the staged changes, for example a forgotten file, to the last commit without changing its message. Caution: this is also only for a commit that has not been pushed yet.
-
git diffShow the changes in files that have not been staged yet, line by line.
-
git diff --stagedShow the changes that are already staged and will be included in the next commit.
-
git diff main...feature/loginShow the changes made on feature/login since it branched off main.
-
git rm old-file.phpDelete the file from the directory and stage the deletion for the next commit.
-
git rm --cached config.local.phpStop tracking the file in the repository, while the file itself stays in the local directory. This is useful for a file that was committed by mistake. Caution: after you push, the file is deleted from the directory of every other copy of the repository that pulls the change, so back it up first.
-
git mv old-name.php new-name.phpRename the file or move it to another directory, and stage the change for the next commit.
-
git restore --staged index.phpRemove the file from the staging area. The changes in the file itself are kept.
History
-
git logShow the list of commits on the current branch, from newest to oldest, with the author, date, and message. Press q to exit the view.
-
git log --oneline --graph --allShow the history of all branches as a graph, one line per commit, so you can see where branches split and were merged.
-
git log -p index.phpShow all the commits that changed the file, together with the changes themselves in each commit.
-
git log --follow -- index.phpShow the history of the file, including the time before it was renamed.
-
git log --author="Israel"Show only the commits by a specific author. You can also search by part of the name or the email address.
-
git log -S "functionName"Find the commits that added or removed the given text, for example to find out when a function was deleted.
-
git show abc1234Show the details and changes of a specific commit by its short ID.
-
git show HEAD~1:index.phpShow the contents of the file as it was in the commit before the last one, without changing the file in the directory.
-
git blame index.phpShow, for each line in the file, the commit, author, and date of the last change to it.
-
git reflogShow every position HEAD has been at in the local repository, including commits removed from the branch by a reset or a rebase.
-
git shortlog -snList the authors by the number of commits each one made, from highest to lowest.
Branches
-
git branchList the local branches and mark the current branch with an asterisk.
-
git branch -aList all branches, including the branches of the remote repository.
-
git branch -vvShow, for each branch, its latest commit, the remote branch it tracks, and how many commits it is ahead of or behind the remote branch.
-
git switch mainSwitch to the main branch and update the files in the directory to match the branch.
-
git switch -c feature/loginCreate a new branch named feature/login from the current position and switch to it.
-
git switch -Return to the previous branch, similar to the cd - command in Linux.
-
git checkout -b feature/loginCreate a new branch and switch to it with the older syntax, equivalent to git switch -c.
-
git merge feature/loginMerge the changes from the feature/login branch into the current branch. Before you merge, switch to the target branch, for example main.
-
git merge --no-ff feature/loginMerge the branch and create a separate merge commit, even when the current branch could be moved forward directly (fast-forward). This keeps a clear record in the history of the branch that was merged.
-
git rebase mainMove the commits of the current branch so they start from the latest state of main, which creates a straight history. Caution: this rewrites the commits, so do not run it on a branch that others are already working on.
-
git rebase -i HEAD~3Open an editor where you can combine the last three commits, change their order, or edit their messages. Caution: use this only for commits that have not been pushed yet.
-
git branch -d feature/loginDelete a local branch that has already been merged. When the branch has not been merged yet, Git refuses to delete it and shows an error message.
-
git branch -D feature/loginForce delete a local branch, even when it contains commits that were not merged into another branch. Caution: you can recover these commits only with git reflog, and only for a limited time.
-
git branch -m new-nameRename the current branch. To rename another branch, specify both names, for example git branch -m old-name new-name.
Remote repositories
-
git remote -vList the configured remote repositories and their fetch and push URLs.
-
git remote add origin git@example.com:user/site.gitConnect the local repository to a remote repository named origin, the common name for the main remote repository.
-
git remote set-url origin git@example.com:user/site.gitChange the URL of an existing remote repository, for example when you switch from an HTTPS connection to an SSH connection.
-
git fetchDownload the new changes from the remote repository without changing the files in the directory and without merging them into the current branch.
-
git fetch --pruneDownload the changes and remove local references to branches that have already been deleted in the remote repository.
-
git pullDownload the changes from the remote branch and merge them into the current branch. This is equivalent to running git fetch and then git merge.
-
git pull --rebaseDownload the changes and move the local commits that have not been pushed yet so they come after the downloaded changes, without a merge commit.
-
git pull --ff-onlyUpdate the branch only when it can be moved forward directly, and refuse to merge when the local branch has diverged from the remote branch.
-
git pushSend the local commits to the remote branch that the current branch tracks.
-
git push -u origin feature/loginPush a new branch to the remote repository and set up tracking, so from then on git push and git pull work without arguments.
-
git push --force-with-leaseReplace the history of the remote branch with the local history, for example after a rebase or an amend. Unlike the --force option, the push fails when the remote branch has changes you have not downloaded yet with git fetch. Caution: the push removes from the remote branch every commit that is not in the local history, so do not use it on a shared branch without coordinating first.
-
git push origin --delete feature/loginDelete the branch from the remote repository. The local branch stays unchanged.
Undoing changes
-
git restore index.phpDiscard the unstaged changes in the file and restore it to the version in the staging area or in the last commit. Caution: you cannot recover the discarded changes.
-
git restore .Discard all unstaged changes in the current directory and its subdirectories. New untracked files are not deleted. Caution: you cannot recover the discarded changes.
-
git restore --source=HEAD~2 index.phpRestore the file in the directory to its state two commits ago, without changing the history. The result appears as a regular change that you can save in a new commit. Caution: uncommitted changes to the file are overwritten.
-
git reset --soft HEAD~1Undo the last commit and keep its changes in the staging area, ready to commit again.
-
git reset HEAD~1Undo the last commit and keep its changes in the files, outside the staging area. This is the default mode, equivalent to the --mixed option.
-
git reset --hard HEAD~1Undo the last commit and discard its changes, along with all uncommitted changes in tracked files. Caution: changes that were not saved in a commit cannot be recovered.
-
git reset --hard origin/mainReset the local branch to exactly match the remote branch. Run git fetch first to update the local copy of the remote branch. Caution: the command discards the local commits that have not been pushed yet and all uncommitted changes.
-
git revert abc1234Create a new commit that undoes the changes of an existing commit, without removing anything from the history. This is the safe way to undo a commit that has already been pushed to a shared repository.
-
git clean -ndShow which untracked files and directories git clean -fd would delete, without actually deleting them.
-
git clean -fdPermanently delete all untracked files and directories, except files that Git ignores according to .gitignore. Caution: check the list with git clean -nd before you run it.
-
git stashSet aside the uncommitted changes and return the tracked files to the state of the last commit, for example before you switch to another branch. New untracked files are not set aside.
-
git stash push -u -m "WIP login form"Set aside the changes together with new untracked files, and add a description to the entry.
-
git stash listList the changes set aside, where the entry stash@{0} is the most recent one.
-
git stash show -p stash@{0}Show the full changes stored in a specific entry, line by line.
-
git stash popRestore the most recent entry set aside to the directory and remove it from the list. When a conflict occurs, the entry stays in the list.
-
git stash drop stash@{1}Delete a specific entry from the list of changes set aside. Caution: the regular commands cannot recover the changes in the entry.
Tags
-
git tagList all the tags in the repository in alphabetical order.
-
git tag v1.0.0Create a lightweight tag on the current commit, which is only a marker with no additional information.
-
git tag -a v1.0.0 -m "First stable release"Create an annotated tag that includes the name of its creator, the date, and the message. A tag like this suits marking official releases.
-
git push origin v1.0.0Push one tag to the remote repository. The regular git push command does not push tags.
-
git push --tagsPush to the remote repository all the local tags that do not exist there yet.
-
git tag -d v1.0.0Delete a tag from the local repository only.
-
git push origin --delete v1.0.0Delete the tag from the remote repository.
The .gitignore file
-
.envA line in the .gitignore file that keeps the .env settings file out of the repository, in every directory of the project.
-
*.logMake Git ignore all files with the .log extension, in every directory of the project.
-
node_modules/The slash at the end of the line means the pattern matches directories only, so Git ignores every directory named node_modules and all its contents.
-
/vendor/The slash at the start of the line limits the pattern to the vendor directory in the root directory of the project only.
-
**/cache/Make Git ignore every directory named cache, at any depth in the project. In this case, the result is the same as the line cache/.
-
!keep.logThe exclamation mark excludes a file from an earlier pattern, so the keep.log file can be added to the repository despite the *.log line. You cannot exclude a file inside a directory that Git ignores entirely.
-
git check-ignore -v storage/app.logShow the line and the ignore file that make Git ignore the file, to help you find a rule that does not work as expected.
-
git rm -r --cached .Stop tracking all files while keeping them in the directory, to apply new .gitignore rules to files that are already tracked. Then run git add . and commit. Caution: after you push, files removed from tracking are deleted from every other copy of the repository that pulls the change.
-
git config --global core.excludesFile ~/.gitignore_globalSet a global ignore file for all repositories on the computer, for example for files created by the operating system or the code editor.
Working on a server
-
ssh-keygen -t ed25519 -C "deploy@example.com"Create an SSH key pair for connecting to a Git hosting service. Add the public key to your account on the service, or to a specific repository as a deploy key.
-
cat ~/.ssh/id_ed25519.pubShow the public key so you can copy it to the settings of the Git hosting service. Caution: do not copy or share the private key, which is in the file without the .pub extension.
-
ssh -T git@example.comTest the connection to the Git hosting service with an SSH key. When the connection works, the service usually shows a welcome message with your username.
-
git config core.sshCommand "ssh -i ~/.ssh/deploy_key -o IdentitiesOnly=yes"Set a specific SSH key for the current repository, for example when the server has several deploy keys for different repositories.
-
git clone git@example.com:user/site.git /var/www/exampleClone the repository directly into the website directory on the server, to prepare for updates with git pull. Caution: when this is the website's root directory, block browser access to the .git directory.
-
git -C /var/www/example pull --ff-onlyUpdate the website on the server to the latest version in the repository, without changing to its directory. The --ff-only option prevents an unexpected merge when the server has local commits that are not in the remote repository.
-
git -C /var/www/example log -1 --onelineShow the current commit in the website directory, for a quick check that the update was applied.
-
git config --global --add safe.directory /var/www/exampleAllow working in a repository owned by another user, which resolves the detected dubious ownership error. Add only known directories whose contents you trust.
-
git config core.fileMode falseMake Git ignore file permission changes, so files whose permissions were changed with chmod are not shown as modified.
Troubleshooting
-
git diff --name-only --diff-filter=UList the files that have a conflict after a merge stopped because of a conflict. In each of these files, the conflict is marked between the lines <<<<<<< and >>>>>>>.
-
git checkout --theirs index.phpResolve a conflict in a file by choosing the version from the branch being merged. The --ours option chooses the version from the current branch, and during a rebase the meaning of the two options is reversed. Then mark the file as resolved with git add.
-
git commit --no-editComplete the merge with the automatically created merge message. Before you run it, resolve the conflict in each file and mark it as resolved with git add.
-
git merge --abortCancel a merge that stopped because of a conflict and return the branch to its state before the merge.
-
git rebase --continueContinue the rebase after you resolve the conflict and mark the files with git add.
-
git rebase --abortCancel the rebase and return the branch to its state before the rebase started.
-
git switch -c rescue-workSave commits created in detached HEAD state in a new branch. This state means you switched to a specific commit rather than to a branch. Without a branch, these commits may be lost after you switch to another branch. When no commits were created in this state, git switch main is enough to return to the branch.
-
git log origin/main..HEAD --onelineShow the local commits that have not been pushed to the remote main branch yet, as a check before you undo a commit. When the commit you want is not in the list, it has already been pushed, so undo it with git revert and not with git reset.
-
git revert HEADUndo the last commit that has already been pushed, with a new commit that undoes its changes. Then push the new commit with git push.
-
git branch recovered abc1234Create a new branch named recovered from a commit whose ID you found in the output of git reflog, which recovers a deleted commit or branch.
-
git cherry-pick abc1234Copy a specific commit from another branch to the current branch, for example a commit created on the wrong branch by mistake.
No matching commands.
Git keeps the full history of every file in a project, lets you go back to any point in the past, and lets a team work on the same code at the same time. Every copy of a repository includes the full history, so you can work and commit changes without an internet connection and sync them with the remote repository later.
A change to a file goes through three stages: you edit it in the working directory, add it to the staging area with git add, and save it to the history with git commit. The changes reach the remote repository only when you push them with git push. To connect to a repository over SSH without typing a password, you can create a key with the SSH key generator.
Two habits prevent many problems. Before you run any command that discards changes or rewrites history, such as reset --hard, clean -fd, or push --force-with-lease, check with git status and git log what is about to change. Also, develop each new feature in a separate branch, not directly in the main branch.
On a Coolify VPS, you can connect a Git repository, such as GitHub or GitLab, and set up automatic deployment every time the code in the repository is updated.
Git commands FAQ
What is the difference between git fetch and git pull?
The git fetch command downloads the changes from the remote repository and does not change the files in the directory, and the git pull command downloads the changes and also merges them into the current branch. With git fetch, you can first check what has changed, for example with git log main..origin/main, and only then decide whether to merge.
How do I undo the last commit?
The right way depends on whether the commit has already been pushed. When the commit is still local, git reset --soft HEAD~1 undoes it and keeps all the changes ready to fix. When the commit has already been pushed to a shared repository, use git revert, which creates a new commit that undoes the changes without rewriting the history.
When should I use merge and when should I use rebase?
Both commands integrate changes from one branch into another, and the difference is the shape of the history. The merge command keeps the history as it was and adds a merge commit, and the rebase command moves the commits so the history looks straight. The common rule is to use rebase only on a local branch that has not been shared yet, and merge on any shared branch.
Why does a file I added to .gitignore still show up in my changes?
The .gitignore file applies only to untracked files, so it has no effect on a file that is already committed to the repository. To fix this, run git rm --cached with the file name and commit. The file stays in the local directory, and from then on Git ignores it.
How do I update a website on a server with Git?
The simple way is to clone the repository once into the website directory on the server, and run git pull --ff-only in that directory for every update. For a secure connection without a password, create a dedicated SSH key on the server and add it to the repository as a read-only deploy key. Add files created on the server, such as environment settings, files uploaded by users, and cache, to .gitignore so they do not conflict with updates.
How do I recover a deleted commit or branch?
In most cases you can recover them, because Git keeps commits that do not belong to any branch for some time. The git reflog command shows all the recent positions of HEAD, and once you find the right ID, the git branch recovered abc1234 command creates a new branch from it. Changes that were never saved in a commit do not appear in the reflog and cannot be recovered this way.