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.

link|improve this question

62% accept rate
Just a tip IMO useful: split the prompt on two lines; something like '\w\n\$ '. – cYrus Feb 9 at 12:34
feedback

2 Answers

up vote 0 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.

link|improve this answer
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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