linuxbashpromptps1

Bash PWD Shortening


I'm looking for a bash function that will shorten long path names to keep my PS1 variable from getting excessively long. Something along the lines of:

/this/is/the/path/to/a/really/long/directory/i/would/like/shortened

might end up as:

/t../i../t../p../to/a/r../l../d../i/w../like/shortened

something that the took the path and a maximum acceptable number of characters to shorten to would be perfect for my .bashrc file.


Solution

  • How about a Python script? This shortens the longest directory names first, one character at a time until it meets its length goal or cannot get the path any shorter. It does not shorten the last directory in the path.

    (I started writing this in plain shell script but man, bash stinks at string manipulation.)

    #!/usr/bin/env python
    import sys
    
    try:
        path   = sys.argv[1]
        length = int(sys.argv[2])
    except:
        print >>sys.stderr, "Usage: $0 <path> <length>"
        sys.exit(1)
    
    while len(path) > length:
        dirs = path.split("/");
    
        # Find the longest directory in the path.
        max_index  = -1
        max_length = 3
    
        for i in range(len(dirs) - 1):
            if len(dirs[i]) > max_length:
                max_index  = i
                max_length = len(dirs[i])
    
        # Shorten it by one character.    
        if max_index >= 0:
            dirs[max_index] = dirs[max_index][:max_length-3] + ".."
            path = "/".join(dirs)
    
        # Didn't find anything to shorten. This is as good as it gets.
        else:
            break
    
    print path
    

    Example output:

    $ echo $DIR
    /this/is/the/path/to/a/really/long/directory/i/would/like/shortened
    $ ./shorten.py $DIR 70
    /this/is/the/path/to/a/really/long/directory/i/would/like/shortened 
    $ ./shorten.py $DIR 65
    /this/is/the/path/to/a/really/long/direc../i/would/like/shortened
    $ ./shorten.py $DIR 60
    /this/is/the/path/to/a/re../long/di../i/would/like/shortened
    $ ./shorten.py $DIR 55
    /t../is/the/p../to/a/r../l../di../i/wo../like/shortened
    $ ./shorten.py $DIR 50
    /t../is/the/p../to/a/r../l../d../i/w../l../shortened