DEV Community

Brent Vanwildemeersch
Brent Vanwildemeersch

Posted on

5 useful Git-commands

Create a new branch

Using the git terminal may still be the fastest way of creating a new branch, even with Git integration tools in code editors as VS Code.

git checkout -b <new-branch-name> master
Enter fullscreen mode Exit fullscreen mode

Rename your Git-branch (local and remote)

Having a branch naming convention is a good practice and will particularly be usefull in support of git automation workflows.
But sometimes you will find your branch not aligned with the set naming convention, and you already pushed code to the remote branch.
With the following commands you can adjust your local and remote branch name

#Checkout the branch you want to rename
git checkout <old-branch-name>

#Rename the branch locally
git branch -m <new-branch-name>

#Delete the old branch from remote 
git push origin :<old-branch-name><new-branch-name>

#Reset upstream branch for the new branch name
git push origin -u <new-branch-name>
Enter fullscreen mode Exit fullscreen mode

Uncommit local commits

Sometimes you can have made a commit, which you now regret and you want to remove. There are several ways to remove/undo these commits

#Keep the changes you made, but undo the commit
git reset --soft HEAD^

#Undo the commit and destroy all made changes
git reset --hard HEAD^

#Destroy/Undo more than 1 commit (2 commits in example) 
git reset --hard||--soft HEAD~2


Enter fullscreen mode Exit fullscreen mode

Delete a file/multiple files from Git-branch (local and remote)

Deleting a file(s) from remote could be useful if the file is deprecated or isn't supposed to be in the git repository in the first place.

#Remove your file(s) locally 
git rm <file-a> <file-b> ...

#Commit your changes 
git commit -m "Commit message"

#Push changes to git
git push
Enter fullscreen mode Exit fullscreen mode

Remove dead branches

When you work on decent sized projects, it can occur that the git-repository has tens or hundreds of branches from previous pull requests.
Most of these branches are probably already merged and deleted on the remote repository, but they still are listed on your local machine.
To delete these dead branches, use the following command

git remote update --prune
Enter fullscreen mode Exit fullscreen mode

Top comments (0)