Skip to content

Showing your git branch in your shell prompt

At some point I found some code to get the git branch name and insert it into the shell prompt. As it was some years ago, sadly I've forgotten the original source, but it wasn't exactly the type of prompt I'm used to, so I tweaked it until I got it the way I prefer. In the first set of brackets, I display the user@host:directory.

Once I cd into a git initialized directory a colored prompt appears with the branch name displayed in gold. For my purposes, this is simple, functional and doesn't result in overly long prompts. Here's what you can expect from any terminal that supports ansi color codes.



To implement the prompt on your server or workstation, simply cut this snippet and paste it into the end of the /etc/bashrc file.

The current way to do this is to create a new file named "gitprompt.sh" in the /etc/profile.d directory, and paste the code below into it. Using vim is a good way to accomplish this task. You need to be root or sudo for this to work of course.

Once the file exists, all the system users will benefit from the prompt in their shell sessions.

Using this prompt, whenever you're in your bash shell, there will be no question of whether or not you are in a git initialized directory, or what your currently checked out branch name is.


# Custom aliases and functions
function parse_git_branch_and_add_brackets {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\ \[\1\]/'
}
PS1="[\u@\h:\W]\[\033[0;33m\]\$(parse_git_branch_and_add_brackets)\[\033[0m\]\$ "
 


Does this work on a Mac? Yes of course!




Defined tags for this entry: , , ,

Linux shell scripting: bad interpreter: No such file or directory

This error pops up for a couple of reasons. At the top of the script there will probably be a line that looks like this:

#!/bin/sh


This is telling Linux that this script should be interpreted using the /bin/sh program. So your first step is to verify that program exists. I tend to use:

which sh


This will typically come back with a response like this:

/bin/sh


This is telling us that the path to the sh program is in fact /bin/sh, matching the path specified at the top of the script. Ok, so what gives? Well, it's possible that this script was made on an operating system that has line ending characters different than linux. This could have been on on a Mac or PC, or the file could have been converted when it was packaged. In this case, you get the relatively misleading bad interpreter: No such file or directory message, which is really trying to look for sh, although you don't get any indication of the fact.

So, how to fix? Read on. Continue reading "Linux shell scripting: bad interpreter: No such file or directory"