Readable Path for Terminal

When working in terminal, I’d like my prompt to look like:


[user@host:.../cocoa/apple/examples]$

I like to know a couple levels above where I am without it taking over the entire screen width. This function will let you show the last 3 levels or the whole path if less. It also shows ~ for your home path. Here is the code to get this to work in your .profile/.bashrc/whatever:


# Prompt that replace console title and uses breadcrumbs
export PS1='\[\e]2;\u@\H \w\a\][\u@\h:`breadcrumbs "$PWD" 3`]\$ '

# Function that returns the last n path components of the specified path after
# replacing $HOME with ~.  Call like:
#     breadcrumbs path n
function breadcrumbs
{
    echo $1 | sed "s|^$HOME|~|" | awk -v n=$2 '{
        # Split the path into components
        count = split($0, components, "/");

        # If there are less than n components, just print the whole path
        if (count <= n) {
            print $0
        } else {
            # Else print the last n components
            if (count > n) {
            	printf ".../"
            }

            for (i = count - n + 1; i < count; i++) {
                printf "%s/", components[i]
            }

            printf "%s", components[i]
        }
    }'
}

4 Comments

  1. Posted August 27, 2006 at 9:10 am | Permalink

    I couldn’t get this to work Andrew, could you check and make sure WordPress didn’t mess it up?

  2. Posted August 27, 2006 at 10:43 am | Permalink

    I got it working, but had to make some pretty heavy changes, you can see what I did at:

    http://files.nnutter.com/public/profile

  3. Posted August 27, 2006 at 8:01 pm | Permalink

    Yes, wordpress has made a mess of this post. All my less than signs are missing.

  4. Posted October 4, 2006 at 6:55 pm | Permalink

    I use zsh, the breadcrumbs thing is built in ;)

    http://docsrv.caldera.com:8457/cgi-bin/info2html?(zsh.info.gz)Prompt%2520Expansion

    %d
    %/
    Present working directory ($PWD). If an integer follows the `%’,
    it specifies a number of trailing components of $PWD to show; zero
    means the whole path.


One Trackback/Pingback

  1. [...] Andrew wrote a tip today to have your bash prompt show the last ‘n’ folders of your current directory. His original suggestions is on his website, Readable Path for Terminal. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*