Knowing useful git commands can greatly help the development workflow. Here are some useful git commands and options that not everyone might know.
1. git status
git status
shows what files have been changed from the current HEAD commit.
When you run git status
, it shows:
If the current local branch is ahead or behind the remote branch (if it exists).
Changed to be committed
Changed not staged for commit.
Changes to be committed are files that have been staged using git add
.
Changes not staged for commit files that have been changed but not staged using git add
.
It is always to run git status
to double-check before you git push
.
1. git add -u -p
git add
adds new or changed files to the staging area. Files must be added to the staging area before git commit
.
The -u
option only stages modified and deleted files, but NOT new files.
The -p
option allows the user to see each changed chunk and choose to stage it or not.
When you use the two -u -p
options together, it allows us to avoid committing unwanted changes and error log files.
2. git checkout -b newbranch
When you want to move uncommitted work to a new branch, you can use git checkout -b newbranch
.
Any uncommitted work will be moved to the new branch.
3. git stash
git stash
stores uncommitted work in a temporary location.
git stash
is useful when you need to switch branches, but do not want to commit the changes just yet.
git stash pop
restores the last stash.
4. git checkout -
git checkout -
switches the current branch to the previous branch.
git checkout -
can be used to switch back and forth between two branches easily.
5. git reset --soft HEAD~1
git reset --soft HEAD~1
undoes the last commit.
6. git commit --amend
git commit --amend
edits the last commit message.