Sunday, 24 February 2013

Delete unused branches from your remote Git repo

Without regular housekeeping, your Git repos can become cluttered with feature branches that were either already merged into master, or just abandoned as simple experiments. Especially on larger projects, things can quickly start to get messy!

How might we go about cleaning these unwanted branches up?

One way would be to delete each branch at a time, using git push combined with our branch name, prefixed with a colon:

git push origin :<unwanted branch>

This works fine for one or two branches, but what if we want to remove many branches in one go?

git br -r | egrep -v "master|<other branches to keep>" | sed "s/\// :/" | xargs -n 2 git push

This script takes all the remote branches, filters them for branches we want to keep, constructs the 'origin :<remote branch>' command suffixes, and then passes each one to git push.

If you're at all nervous, back up your repo locally first!

Sunday, 27 January 2013

Creating aliases in Ubuntu

Aliases are handy shortcuts that allow you to quickly perform frequently executed statements in the bash terminal. To see the currently active aliases simply type:

 $ alias

On my fresh install of Ubuntu this returns:

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'

Typing ll in other words is equivalent to typing ls -alF. Nice. How about adding an alias of our own?

I frequently visit /mnt/Storage/tools on my filesystem - quite a mouthful (handful?) to type everytime. To add an alias to navigate to this folder I can simply enter:

$ alias tools='cd /mnt/Storage/tools'

Now all I need to do is type tools from anywhere in the terminal to jump straight to that location.

However, we've still one small problem - this alias will only remain available for the duration of the current bash session.

To create aliases that will be available the next time we fire up the terminal, simply create a ~/.bash_aliases file and declare them there. Once you've saved the file, type:

$ source ~/.bashrc

to refresh the current session and you're done. Happy aliasing!