Wednesday, July 4, 2012

Ultimate bash prompt

The standard bash prompt on most systems is very unusable. Most of the time, it's just something like bash-3.2#, which doesn't give you much information. Knowing the machine you're working on and your current working directory is crucial, and if your prompt provides you this information this can make your life a lot easier.

So here it is: My bash prompt. It looks like this:

in GNOME

on mac (Terminal.app)
Features are:
  • Display of hostname up to first '.'
  • Display of path
  • red SU in front when superuser/root
  • display of hostname up to first '.' and directory in xterm/mac title
In my opinion, that's all information you need most of the time (except for maybe some git/svn information). I added the shortened hostname in front because i'm working on different systems a lot and this just helps distinguish them from the window title.
You can add more to it, flashing colors and stuff, but it just gets unusable at some point especially when you have long directory names.
Here is the code: 
#!/bin/bash
# this sed line returns everything up to the first . in hostname
# ex. linuxbox.university.gov -> linuxbox
SHORT_HOSTNAME=`hostname | sed 's/\([^\.]*\).*/\1/'`

#LONG_HOSTNAME=`hostname -f`

NOCOLOR="\[\e[0m\]"
BRACKETCOLOR="\[\e[1;30m\]"
DIRCOLOR="\[\e[1;34m\]"
HOSTCOLOR="\[\e[1;32m\]"

# add SU in red if root/superuser
[[ $EUID -eq 0 ]] && HOSTCOLOR="\[\033[1;31m\]SU $HOSTCOLOR"

# command executed just before bash displays a prompt
# here it is set to change xterm's (also mac terminal) title string to
# hostname currentDirectory
PROMPT_COMMAND='echo -ne "\033]0; $SHORT_HOSTNAME `dirs`\007"'

# the prompt
PS1="$HOSTCOLOR$SHORT_HOSTNAME $BRACKETCOLOR[$DIRCOLOR\w$BRACKETCOLOR] $NOCOLOR"
You can just copy it in your ~/.bashrc or save it as ~/prompt.sh and add a source prompt.sh in your ~/.bashrc .

Note: Of course this is not the ultimate bash prompt, every advanced user will have an own customized prompt. But I hope it's a good place to start :-).

Here's some more information:
http://wiki.ubuntuusers.de/Bash/Prompt
https://wiki.archlinux.org/index.php/Color_Bash_Prompt

Enjoy!
- Martin

No comments:

Post a Comment