Shorter directory text in Bash prompt
Rather helpfully, David Goodwin left a comment about how he shortens the space taken up by the directory section of his terminal’s PS1 prompt by using a Bash script to remove the middle portion.
This is a really good idea, so I ported it into my PS1 set up which resulted in some rearranging and thought I’d share here as I modified for OS X and I don’t want to lose it!
The relevant portion of my .profile is:
# Git information for prompt if [ -f $(brew --prefix)/etc/bash_completion.d/git-prompt.sh ]; then . $(brew --prefix)/etc/bash_completion.d/git-prompt.sh fi GIT_PS1_SHOWDIRTYSTATE=true GIT_PS1_SHOWUNTRACKEDFILES=true # Shorten current directory - Based on function by David Goodwin function shorten_pwd() { LENGTH="40" PART1="10" PART2="27" DIR=`echo "${PWD}" | sed "s/\\/home\\/$USER/~/" | sed "s/\\/Users\\/$USER/~/"` if [ ${#DIR} -gt $(($LENGTH)) ]; then echo "${DIR:0:$(($PART1))}...${DIR:$((${#DIR}-$PART2)):$PART2}" else echo "$DIR" fi } # Set prompt prompt_cmd () { LAST_STATUS=$? local COLOUR_RESET='\[\e[0m\]' local BLACK='\[\e[0;30m\]' local RED='\[\e[0;31m\]' local GREEN='\[\e[0;32m\]' local YELLOW='\[\e[0;33m\]' local BLUE='\[\e[0;34m\]' local PURPLE='\[\e[0;35m\]' local CYAN='\[\e[0;36m\]' local WHITE='\[\e[0;37m\]' local BOLD_BLACK='\[\e[1;30m\]' local BOLD_RED='\[\e[1;31m\]' local BOLD_GREEN='\[\e[1;32m\]' local BOLD_YELLOW='\[\e[1;33m\]' local BOLD_BLUE='\[\e[1;34m\]' local BOLD_PURPLE='\[\e[1;35m\]' local BOLD_CYAN='\[\e[1;36m\]' local BOLD_WHITE='\[\e[1;37m\]' PS1="$BLACK\u@\h" # user@host PS1+=" " PS1+="$BLUE" PS1+=$(shorten_pwd) # current directory (usually \w) PS1+=" " PS1+="$RED" PS1+=$(__git_ps1) # git status PS1+="$COLOUR_RESET" PS1+='\$ ' } PROMPT_COMMAND='prompt_cmd && tab_title'
There are three sections here. Firstly we ensure that git-prompt.sh is loaded and configure a couple of settings for it. Then we write a function called shorten_cwd() based on David’s script. The main changes here are that I also look for /Users/$USER as that’s where OS X stores home directories and that I don’t split in the middle. Finally we define prompt_cmd() to set PS1 in a way that I understand and assign it to PROMPT_COMMAND along with tab_title.
The end result looks like this:
I think Oh My Zsh can you help ))) http://ohmyz.sh/
Hi Rob,
thanks for the trick. I've slightly modified the shorten_pwd() function to bind the value of the
PART2
variable to the number columns of the terminal:Hope it can be useful.
Ciao!
Lorenzo,
That's a clever idea. Thanks for sharing!