Jeff Terrell

Jeff Terrell
Ph.D. Candidate
Department of Computer Science
University of North Carolina at Chapel Hill

jsterrel AT cs.unc.edu
(919) 962-1791 (office)

tcsh-style prompt in bash

Setup

tcsh is version 6.12.00, bash is version 2.05b.0. tcsh has the capability to do some nifty directory munging, like so:

[kyptin:~/code/dist-sys/proj] > cat ~/.tcshrc
set prompt = "[%m:%c3] %# "
[kyptin:~/code/dist-sys/proj] > pwd
/home/jsterre/code/dist-sys/proj

A friend of mine who has used tcsh for a while wants to give bash a try, but he doesn't want to sacrifice his spiffy prompt. The prompt does home directory substitution (i.e. /home/user/ becomes ~), and displays the deepest 3 directories.

Background

bash has lots of crazy parameter expansion operators. Read up on them in the "Parameter Expansion" section of the bash(1) manpage. However, bash still doesn't quite have the power that I need in this case, so I must resort to using Perl. It's suboptimal to need a separate shell script for the prompt. Do let me know if any of you wizards out there come up with a solution.

Resolution

$ cat > ~/prompt.sh
#!/bin/sh
echo ${PWD/$HOME/~}/ | perl -ne 'chomp; @a=split(m#/#); $a=join("/",@a[-3..-1])."/"; $a=~s#^/+#/#; $a=~s#^/~#~#; print "$a"'
^D # that's CTRL-D
$ chmod 755 ~/prompt.sh

Then, change your ~/.bashrc to include the following line:
export PS1='\[\033[01;32m\]\u@\h \[\033[01;34m\]`$HOME/prompt.sh` \$ \[\033[00m\]'

You'll be left with a pretty spiffy prompt, if I do say so myself. Check it out:

jsterre@kyptin ~/ $ cd code/dist-sys/
jsterre@kyptin ~/code/dist-sys/ $ cd proj/demos/
jsterre@kyptin dist-sys/proj/demos/ $ cd /usr/share/doc/bash-2.05b-r9/
jsterre@kyptin share/doc/bash-2.05b-r9/ $

Resolution 2

Matthew Boyce offered another solution. His doesn't need a separate script. I've included the text of his email below.

In your PS1 variable, instead of including \w or your perl script:

$(echo '\w' | grep -o '\(^/\)\?\([^/]*/\)\{0,2\}[^/]*$')

Explaining the above grep pattern from back to front:

(This means that if you're only two directories up from root it'll print the root '/')

This removes the need for a special purpose script.

References

articles/tcsh-prompt.php: Last Modified: 12/03/07@18:02:12 | Size: 3374 bytes | View Source