Customising the BASH prompt

intro:
The Unix BASH shell is customisable. This covers one way of setting your PS1 so it doesn't get too long when in a deeply nested file hiearchy. It assumes you already know what PS1 is etc.

subject:
bash PS1 prompt customisation

content:
Create a file called e.g. ~/bin/prompt :

#!/bin/bash

LENGTH="50"
HALF="$(($LENGTH/2))"

if [ ${#PWD} -gt $(($LENGTH)) ]; then
echo "${PWD:0:$(($HALF-3))}...${PWD:$((${#PWD}-$HALF)):$HALF}" | \
sed s/\\/home\\/$USER/~/
else
echo "$PWD" | sed s/\\/home\\/$USER/~/
fi
You'll note from the above that if your prompt length is greater than $LENGTH, it is truncated (snipping a bit out of the middle). This stops the prompt from becoming too unwieldy.
To use it, edit your ~/.bashrc and include something like :

export PS1='[\u@\h:$($HOME/bin/prompt)]\$ '
Giving something like :

[david@fitz:/tmp/abcdefghijklmnopq...bcdefghijklmnopqrstuvwxyz]$ pwd
/tmp/abcdefghijklmnopqrstubvwxyz01234567890/abcdefghijklmnopqrstuvwxyz

Obviously you can change the length value in the prompt command to reduce or increase this limit as necessary.

Technorati Tags:

Comments

Instead of sed

Instead of
sed s/\\/home\\/$USER/~/

I'd suggest:

sed "s|/home/$USER|~|"

Or even (since on my machine my homedir is /user/home/$USER :

sed "s/$HOME/~/"

To ensure that it doesn't match such things in the middle of the string, then change to

sed "s/^$HOME/~/"

Finally an improvement would be if the homedir substitution was done
automatically BEFORE the LENGTH decision was taken (also means
that above code I ave just shown appears just the once)

I'll leave that as an exercise for the reader!

enjoy

JK

Thanks

This is exactly the solution I was looking for. Thanks!

Hello, As I use many

Hello,

As I use many terminals in different windows size, i'd like the prompt truncation to fit the terminal's size. Here are the modified code.

in .bashrc:

shopt -s checkwinsize #bash ENV contains COLUMNS variable
export PS1='\u@\h:$($HOME/bin/prompt $COLUMNS) $ '

in $HOME/bin/prompt:

#!/bin/bash
MINLENGTH=55
if [ $MINLENGTH -lt $1 ]; then
LENGTH=$(($1-$MINLENGTH))
else
LENGTH=$MINLENGTH
fi
HALF="$(($LENGTH/2))"
if [ ${#PWD}...

++

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
We don't take kindly to automated nonsensible adverts around here.