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.

  • Just a tip IMO useful: split the prompt on two lines; something like '\w\n\$ '.
    – cYrus
    Feb 9, 2012 at 12:34

3 Answers 3


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
        echo "..."${1: -$len}
        echo $1
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
        while [ ${#p} -gt $2 ]; do
            p="/"$(echo "$p"|cut -d"/" -f3-)
        echo "..."$p
        echo $1
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.


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


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.

  • macos native bash version <4. So it is not supported
    – Dudi
    Feb 5, 2017 at 9:31

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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