Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

On my Mac OS X 10.6, I have my prompt set to

PS1='\[\033[01;32m\][\w\[\033[00m\]\[\033[01;34m\]$(__git_ps1 " (%s)")\033[01;32m\]]\[\033[00m\]\$ '

How can I limit the number of directories in my prompt? The \w part?

This is because when I go deep in a directory tree, the prompt takes up the whole width of the terminal.

share|improve this question
    
Just a tip IMO useful: split the prompt on two lines; something like '\w\n\$ '. – cYrus Feb 9 '12 at 12:34
up vote 3 down vote accepted

you already use a function in your prompt for your git branch name probably, which is nice, so just do the same for your path:

# shorten a path in $1 to max of $2 characters, prepending a "..."
function __shortpath {
    if [[ ${#1} -gt $2 ]]; then
        len=$2+3
        echo "..."${1: -$len}
    else
        echo $1
    fi
}
PS1='\[\033[01;32m\][$(__shortpath "\w" 50)\[\033[00m\]\[\033[01;34m\]$(__git_ps1 " (%s)")\033[01;32m\]]\[\033[00m\]\$ '

It will limit the path to the last 50 character. This is an example. You could also think of cutting off only at a slash, but that make it more difficult.

# drops first portion of a path $1 if length is greater than $2
function __droppath {
    if [[ ${#1} -gt $2 ]]; then
        p=$1
        while [ ${#p} -gt $2 ]; do
            p="/"$(echo "$p"|cut -d"/" -f3-)
        done
        echo "..."$p
    else
        echo $1
    fi
}
PS1='\[\033[01;32m\][$(__droppath "\w" 50)\[\033[00m\]\[\033[01;34m\]$(__git_ps1 " (%s)")\033[01;32m\]]\[\033[00m\]\$ '

Maybe it's also a good idea to secure the while loop by checking if new length is shorter than old length (otherwise quit) or if new length is 0 in which case you may return the last value of $p - or continue with __shortpath.

share|improve this answer

I personally don't have any paths in my prompt, I don't like how it moves the prompt location, even if it's cut down.

I put the current location in the title bar:

USER=$(/usr/bin/id -un)
HOSTNAME=$(uname -n)
HOSTNAME=${HOSTNAME%%.*}
PROMPT_COMMAND='echo -ne "\e]0;$USER@${HOSTNAME}: $(pwd -P)\a"'

The command for USER getting the current user is linux/gnu flags, MacOSX/bsd flags may differ.

share|improve this answer

Have you looked at PROMPT_DIRTRIM (bash setting, check man bash):

PROMPT_DIRTRIM

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see PROMPTING below). Characters removed are replaced with an ellipsis.

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.