Ubuntu – trim the terminal command prompt working directory

bashcommand lineprompt

When using the terminal in a deep folder structure sometimes the prompt can take up most of the line. Is there any way in which I can trim the working directory? I know I can do

PS1="\W >"

to only print the current directory and not the full path, but is there a way to have something like:

/home/smauel/de...ther/folder >

Best Answer

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.