Friday, November 16, 2018

Incorporate Git and IBM Cloud information into BASH command prompt

Many of you know that I love to use the command line. Because my day to day work includes interfacing IBM Cloud and GitHub, I have changed the BASH configuration to include related information into the command prompt. Here is what I did and how it looks like.


I added the following lines to my ".bashrc" file. The first line is a function git_branch used to extract information about the current Git branch. It's value is assigned to BRANCH later on. HOST and LOCATION are pretty standard except that longer path are shortened to essential information. The function cloud_region extracts the region and current account from the IBM Cloud CLI configuration. Finally, the line with PS1 configures the actual primary command prompt (2 lines) with the previously defined components.


git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'; }
HOST='\e[02;36m\h'; HOST='@'$HOST
LOCATION=' \e[01;34m`pwd | sed "s#\(/[^/]\{1,\}/[^/]\{1,\}/[^/]\{1,\}/\).*\(/[^/]\{1,\}/[^/]\{1,\}\)/\{0,1\}#\1_\2#g"`'
BRANCH=' \e[00;33m$(git_branch)\[\e[00m]\n\$ '
cloud_region () { cat ~/.bluemix/config.json | jq -rc '[.Region,.Account.Name]'; }
CLOUD_REGION=' \e[00;34m$(cloud_region) '
export PS1='['$USER$HOST$LOCATION$CLOUD_REGION$BRANCH


Once done, everything looks like this in action:
Henrik's bash environment

Without looking it up, I always know under which cloud account I am operating and the current project branch I am coding on.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik) or LinkedIn.