Create a fixed-length bash shell prompt

Dec 21, '01 08:29:29PM

Contributed by: dlandrith

This tip is stolen from instructions in the Bash Prompt HOWTO. It's not terribly innovative, and most Unix distributions (MacOS X included) come with a tolerably decent default prompt; consequently, even many very experienced Unix users don't know a lot about prompt configuration (I certainly didn't). But if you compile and install bash on MacOS X, you'll find that you are left with a very unsatisfactory default prompt. It was this problem that led me to sniff this information out.

This tip solves the dilemma of whether to use \W (current directory without path) or \w (complete path to current directory) in the prompt. On the one hand, \W doesn't contain the path (am I in /etc or /usr/local/etc?), but \w (which contains the path) can monopolize the command line. The solution: Include only the last x characters of the current working directory.

This tip will work swimmingly with bash, and maybe someone can explain how to do the same thing with tcsh in the replies (I'm a bash partisan myself, and I heartily recommend it to anyone who has to use the shell regularly). Read the rest of this article for instructions on creating a fixed-length bash shell prompt.

Include the following in your /etc/profile or ~/.profile file (according to your preference):

function prompt_command {
# How many characters of the $PWD should be kept
local pwd_length=23
if [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then newPWD="$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else newPWD="$(echo -n $PWD)"
fi
}

PROMPT_COMMAND=prompt_command

export PROMPT_COMAND
Now, use $newPWD in place of \W or \w in your PS1 environment variable. For example, when I'm in my home directory, my prompt looks like this:
[username@hostname:/Users/username]$
And when I'm in /Users/username/Documents/Downloads, my prompt looks like this:
[username@localhost:ame/Documents/Downloads]$
Bonus: If you want to have a universal prompt definition (i.e., you want to place it in /etc/profile, and still want to get $ for users and # for root, then you can add the following to /etc/profile:
if [ "$UID" = "0" ]
then TERMINUS="#"
else TERMINUS="\$"
fi
Then, put $TERMINUS at the end of your PS1 definition. My prompt is defined as follows:
PS1="[\u@\h:$newPWD]$TERMINUS "
export PS1
This gives me a fixed number of characters for the PWD listing so that it doesn't monopolize my screen. It also gives me a $ for users and # for root.

Comments (22)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20011221202929846