Frontend Mayhem

Pimp My Terminal

May 09, 2017

As software developers, we spend a lot of time staring at the good old terminal. By default, terminal looks rather dull. However, under that boring black & white layout, there are plenty of highly customizable options.

In this blog post, we’re going to customize the command prompt so that it looks cool & also gives us extremely useful information.

Note: This post was written for OSX. Customizing terminal in other environments such as Linux should be fairly similar.

Emojis 🎉

Let’s be honest here. Life is incomplete without emojis. 😍 We’re going to add some emoji awesomeness to our terminal.

Open the terminal & modify the .bash_profile in your preferred editor. One such example is nano

nano ~/.bash_profile

Add a new line at the bottom of the file & add the following code

PS1=🎉

Save your changes and reload the .bash_profile file by using the following command.

source ~/.bash_profile

Hurrah! You should see the 🎉 emoji as your terminal prompt now.

The next step is to randomize the emoji every time the terminal restarts. We will do this by picking a random emoji from a hard-coded list.

In the example above, EMOJIS is a hard coded list of emojis. Feel free to throw any emoji you like in there and as many as you want.

RANDOMEMOJI just grabs a random element of that array of emojis. I have 36 emojis so I have capped the random number to that value by using RANDOM%36.

Save the file & reload the source profile several times. You should see a new emojis pop up every time. Not bad eh!

Username

Emojis are cool but our prompt isn’t very useful right now. The next thing I’d like to add is the username I’m logged in as. Edit the bash profile file & add \u at the beginning of the PS1 variable.

Now your PS1 should look like this PS1="\u $RANDOMEMOJI ". Save & reload the bash profile. Voila!

Current working directory

The next thing we’re going to add to the prompt is the current working directory. Adding the current working directory is as simple as adding \w to the PS1 variable.

Git branch

In my opinion, this is one of the most useful things to add to the prompt. In order to accomplish this, we will write a function to parse the git branch information & add that to the PS1

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

PS1="\u@\w \$(parse_git_branch) $RANDOMEMOJI $ "

Colors

We have a lot of useful information but let’s be honest, it could use a bit of color.

Let’s start off by defining a few variables that will hold the color values

yellow="\e[1;33m";
white="\e[1;37m";
cyan="\e[1;36m";

Now change the PS1 variable

PS1="\[${yellow}\]\u@\[${white}\]\w: \[${cyan}\]\$(parse_git_branch) $RANDOMEMOJI \[${white}\]$ "

Save & reload. You should a beautiful prompt similar to this

That’s it. We have a colorful, exciting & useful prompt.


Watandeep Sekhon

Written by Watandeep Sekhon.
Website / Twitter / LinkedIn / Instagram