Shorter Bash Prompts

4 September 2009

I use Java a lot, and the common practice of naming java packages with long URI-derived namespaces often leads to my bash prompt becoming extremely long. Here’s a script to display an abbreviated path on the bash prompt.

The prompt definitions and script below will display a shortened string derived from the path by taking the first letter from each path segment, and the last segment in its entirity.

For example, the following terminal prompt inside a hypothetical Eclipse plugin I might be developing:

michael@kothar ~/dev/workspace/net.kothar.shiny/src/net/kothar/shiny/actions$

would be abbreviated as:

michael@kothar ~/d/w/n/s/n/k/s/actions$

To most that probably doesn’t mean much, but I think most developers have a good idea what’s in their directory structures, and can probably work out pretty quickly where they are. There’s always a call to the trusty pwd command if you are feeling lost. In some projects I have at work, the package names are even longer, so the reduced amount of text to parse is quite welcome.

Here’s what you need:

New prompt definition (with colours):

PS1="${debian_chroot:+($debian_chroot)}\[\033[00;32m\]\u@\h\[\033[00m\]:\[\033[00;34m\]\$(shortpath)\[\033[00m\]\$ "

Or more simply (without colours):

PS1="\$(shortpath)\$ "



use Cwd;  
my $path = &Cwd::cwd();  

# Replace the 'home' segment with a tilde  
$path =~ s/^$ENV{'HOME'}/~/;  

my @segments = split(/\//, $path);  

my $shortpath = "";  
while (my $segment = shift @segments) {  
	if (@segments) {  
		$shortpath .= substr ($segment, 0, 1) . "/";  
	else {  
		$shortpath .= "$segment";  
print $shortpath;