Git Commands
Summary of commonly used Git commands grouped by task.
1. Create Branches
List every branch.
git branch -a
Switch to the existing develop
branch.
git checkout develop
Create and check out a new branch (for example, develop
).
git checkout -b develop
Delete the testing
branch once it's merged.
git branch -d testing
2. Save Changes
Check the repository status.
git status
Inspect the pending changes in detail.
git diff
Stage a file for the next commit.
git add README.md
Unstage a file before committing.
git reset README.md
Note:
git reset
reverses the effect ofgit add
.
Commit staged changes with a descriptive message.
git commit -m "File README.md created"
View the recent history.
git log
Push your changes to the remote repository:
git push origin master
git push origin develop
3. Undo Changes
You can discard local modifications and restore the version stored in the repository.
Restore a file to its last committed state.
git checkout README.md
Note:
git reset --hard
discards all local changes.
git reset --hard origin/master
4. Merge Branches
Fetch the latest remote changes without merging them.
git fetch origin develop
Retrieve and merge remote changes into your branch.
git pull origin develop
Merge develop
into master
, creating a new merge commit on master
.
git checkout master
git merge develop
5. Try Previous Commits
git stash
lets you save the current working tree so you can test other changes without losing your progress.
List the saved stashes.
git stash list
Clear all saved stashes.
git stash clear
Stash the current state (for example, while on develop
).
git stash
Show the commit history in a single line per entry.
git log --oneline
c41d891 (HEAD -> develop) linter configured
325c062 LICENSE added
e8ac361 config added
b92614b README created
d1aaf40 Initial commit
Temporarily check out a specific commit.
git checkout e8ac361
When you're done, return to the previous branch and reapply the stash.
git checkout develop
git stash apply
6. Amend the Last Commit
Note: Use these commands only before pushing your commits; rewriting shared history can disrupt teammates.
After running git add
, fold the changes into the last commit:
git commit --amend --no-edit
Update the last commit message.
git commit --amend -m "File README.md created (modified)"
Warning: if the commit is already published, forcing a push should be a last resort—use it at your own risk because it can overwrite other people's work.
git push -f origin develop
References
Published: April 30, 2020