trim the terminal command prompt working directory

by smauel   Last Updated February 19, 2017 00:02 AM

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 >

Answers 5

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:

December 16, 2010 12:22 PM

Create a small python scrip which implements the desired trimming logic.

Example: ~/

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) > 30:
    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 ~/"'

If you are ok with the result just append the command into your ~/.bashrc

João Pinto
João Pinto
December 16, 2010 12:54 PM

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.:


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")]\$ '
March 08, 2011 21:19 PM

I like this one most, PS1="[\W]\\$ "

March 03, 2014 08:13 AM

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##*/}"

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 >  
Chris Sullivan
Chris Sullivan
January 06, 2017 07:12 AM

Related Questions

How can I shorten my command line (bash) prompt?

Updated September 19, 2015 13:01 PM