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>"