trim the terminal command prompt working directory
If you are using bash4 (Ubuntu 9.10 and newer has bash4), the easiest option is to just set the PROMPT_DIRTRIM variable. e.g.:
PROMPT_DIRTRIM=2
For one similar to João Pinto's example, (that'll work in older bash versions and ensures that the path component is never longer than 30 characters), you could do something like this:
PS1='[\u@\h:$(p=${PWD/#"$HOME"/~};((${#p}>30))&&echo "${p::10}…${p:(-19)}"||echo "\w")]\$ '
Create a small python script which implements the desired trimming logic.
Example: ~/.short.pwd.py
import os
from socket import gethostname
hostname = gethostname()
username = os.environ['USER']
pwd = os.getcwd()
homedir = os.path.expanduser('~')
pwd = pwd.replace(homedir, '~', 1)
if len(pwd) > 33:
pwd = pwd[:10]+'...'+pwd[-20:] # first 10 chars+last 20 chars
print '[%s@%s:%s] ' % (username, hostname, pwd)
Now test it, from a terminal:
export PROMPT_COMMAND='PS1="$(python ~/.short.pwd.py)"'
If you are ok with the result just append the command to your ~/.bashrc
.
Another way around that problem is to include a line break into PS1, so that the working directory and the actual prompt appear on separate lines, for example:
PS1="\w\n>"
Add this to the bottom of your ~/.bashrc
split_pwd() {
# Only show ellipses for directory trees -gt 3
# Otherwise use the default pwd as the current \w replacement
if [ $(pwd | grep -o '/' | wc -l) -gt 3 ]; then
pwd | cut -d'/' -f1-3 | xargs -I{} echo {}"/../${PWD##*/}"
else
pwd
fi
}
export PS1="\$(split_pwd) > "
Admittedly this could probably be cleaner, but I wanted to get a crack at it.
Expected output for directories more than three layers deep.
/home/chris/../Node Projects >
Expected output for directories from Desktop and back.
/home/chris/Desktop >
/home/chris >
/home