Adding git branch and aws profile to your bash prompt…

As a consultant who works in AWS for numerous clients, one of the most important things to keep track of is which AWS CLI profile am I currently on. To help clarify this, I’ve recently added the AWS profile to my bash prompt to remove all doubt. In addition, I’ve added a prompt for the git branch that I’m currently on. I don’t know if I’ll keep both of these around as it’s added some latency to my prompt returning promptly, but so far it’s useful.

To do this, add the following to your ~/.bashrc:


    git_branch() {
      git branch > /dev/null 2>&1
      if [[ $? -gt 0 ]]
      then
        echo "(none)"
      else
        git_branch=$(git branch | awk '/\*/ {print "("$2")"}')
        echo "${git_branch}"
      fi  
    }
    
    aws_profile() {
      aws_profile=$(aws configure list | egrep profile | awk '{print "("$2")"}')
      if [[ "${aws_profile}" == "(<not)" ]]
      then
        echo "(none)"
      else
        echo "${aws_profile}"
      fi  
    }
    
    export PS1='\n-$?- \u@\h \w >\ngit branch:   $(git_branch)\naws profile:  $(aws_profile)\n\n> '

Note that this will over-write any PS1 that you might have already setup, so use caution. This results in a multi-line prompt that looks like the following:

-0- username@hostname ~/consulting >
git branch:   (master)
aws profile:  (test-dev-account)

> 

To get the new prompt, either logout and login, or source the .bashrc file, ie:

. ~/.bashrc

This prompt is very useful as it provides the return code of the last command (-0-), the user@hostname, the current location on disk, and then two lines with the git branch of the current repository, and then the aws profile that is currently active. The prompt then follows up with two newlines and an angle bracket for the cursor.

Leave a Reply

Your email address will not be published. Required fields are marked *