Useful daily git commands
Here I want to collect some useful frequently used git commands.
Create a branch
git switch -c new-example-branch-name
Delete a branch
Your branch can be just in one place or both. If it exists locally and remotely, then execute both commands.
Delete local branch
git branch -D example-branch-name
the -D parameter forces the deletion
Delete remote branch
git push origin --delete example-branch-name
Cleanup/Prune tracking branches
If there are local branches that aren't anymore available on remote. This command prunes the tracking branches.
git remote prune origin
Going back to a previous commit
You want to go back to a previous commit, then go with the following commands.
If you want to go back to a specific commit and delete all changes in between, then go with the argument --hard. It will move the state to that commit:
git reset --hard [COMMIT_ID]
If you want to keep the changes and just want to move the HEAD, then go with the argument --soft. This keeps the changes to the files in place:
git reset --soft [COMMIT_ID]
If you want to go back n commits, then you can go with the following commands:
git reset [--hard|--soft] HEAD~[n]
n is for the count of commits back from the HEAD. One Commit back is
git reset --hard HEAD~1
Rebase for changing old commit messages
If you want to change old commit messages you can do that with a git rebase. The best way to start is to start git rebase in the interactive mode. You specify how many commits you want to go back starting at the HEAD to rename specific ones. This is the command:
git reset -i HEAD~5
Here you can edit the last 5 commits. The argument -i is the short form of --interactive
Now the text editor should open and you can type in the command in front of the commit-id. In our case to rename the message it is rewrite:
pick 2e42330 chore: remove comments
pick 2e1aac7 feat: feture 3
pick 54d8c42 feat: feature 2
pick 569a4f5 fix: fix 1
rewrite 33e4700 FEATURE 1
This part is still in development....
Edit .gitignore
If there are files that aren't excluded by the .gitignore file, but they are allready tracked, you can do the following to clean you tracked files.
First remove all tracked files. After that, add all files (this time considering the .gitignore file)
git rm -rf --cached .
git add .
Be aware that you are in the root directory from where you want the .gitignore file to track files.