Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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 >

share|improve this question

5 Answers 5

up vote 7 down vote accepted

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

Example: ~/.short.pwd.py

import os
from commands import getoutput
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 ~/.short.pwd.py)"'

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

share|improve this answer
    
Not to ask the obvious, but how exactly do we append the command to the ~/.bashrc? Would it just be pasting that last line at the bottom of the file? –  FloatingRock Jul 4 at 10:31

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")]\$ '
share|improve this answer

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>"
share|improve this answer
    
Similar to thiis, is to not change your PS1 prompt, but to just start your command with a \ and press Enter. This forces the command to begin on the next line with the PS2 prompt, which is usually > ... (I hadn't thought of it until I saw your suggestion :) –  Peter.O Dec 16 '10 at 19:36

Look through the solutions at stackoverflow.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.