Intro
Let’s say you had a long sprint with a lot of completed tasks with a branch for each of them and you no longer need them on your machine. You want to delete all your local branches but they are too many to delete one by one.
Solution
$ git branch | grep -v "excepted_branch" | xargs git branch -D
Breakdown
Now let’s see what we did and maybe why.
We are linking 3 commands and passing the results from one command to another with the help of |
(pipeline).
First, we are going to list all the current branches in your repository.
$ git branch //
After that, we need to filter the results. This time grep
is a great tool.
grep
is used to search within text files using regular expressions (regex).
In our case we are going to use grep
to filter all the branches except the one we don’t want to delete. We are going to do that by using
-v
option, which prints all the lines except the one that fits the regex, in our case the branch name.
grep -v "excepted_branch"
We should first verify if the list contains branches that we don’t want to be removed.
$ git branch | grep -v "excepted_branch"
After we made sure that the list contains what we want, we are going to pass the list to the next command so that we can remove them.
xargs
is perfect for this, it takes the input from the previous command and converts it to arguments for the next command.
$ xargs git branch -D