8

I can't remember where, but I've already seen the bash prompt's current path shortened in an interesting way: every directory contained in the path (excepted the last one) is replaced by its first letter only. For instance: path/to/some/directory would be shortened to p/t/s/directory.

How can I reproduce that behavior ?

2
  • You can't directly do this in PS1. You would need to set PS1 to contain a variable (PS1='${SHORT_PWD}\\$') and update that variable in $PROMPT_COMMAND. Mar 8, 2013 at 1:30
  • @Gilles 'SO- stop being evil' sure you can do it directly, if you use double quote you need to backslash \$() command substitutions though
    – user986805
    Oct 29, 2019 at 7:07

4 Answers 4

9

After playing with this for a while I got the answer you require:

Add this to your .bashrc file in your home directory, exit the terminal and renter it and you will get you prompt.

PS1='$(eval "sps")$ '
sps() {
   echo "$PWD" | sed -r 's|/([^/]{,2})[^/]*|/\1|g'
}

It uses the declared function sps() to evaluate the path every time the variable PS1 which is the prompt, is displayed

ie

/ho/de/De/Ap/Ti$ pwd
/home/deth/Desktop/Apps/Tivo
/ho/de/De/Ap/Ti$ 

Or...if you insist on the one letter

PS1='$(eval "sps")$ '
sps() {
   echo "$PWD" | sed -r 's|/(.)[^/]*|/\1|g'
}

Which displays:

/h/d/D/A/T$ pwd
/home/deth/Desktop/Apps/Tivo
/h/d/D/A/T$ 
1
  • Thanks Meer. My prompt is actually removing the user@pc part. How can I handle this?
    – Alex
    Dec 28, 2015 at 9:18
3

To truncate all directory names except the last one:

PS1='$(eval "sps")$ '                                                                                
sps() {                                                                                              
    python -c "import sys; dirs = sys.argv[1].split('/'); print '/'.join(d[:1] for d in dirs[:-1]) + '/' + dirs[-1]" $PWD
}
1
  • This doesn't work when I change the directories? Sep 7, 2017 at 6:16
2

shorten all names except the last one without python:

user:/h/u/D/C/current$ 
sps() {
    echo `dirname $PWD` | sed -r 's|/(.)[^/]*|/\1|g'
}
PS1='\u:$$(eval "sps")/\W\$ '
1

Here is my solution to shorten the path relative from $HOME, except the last directory:

sps() {
    current_path=${PWD/#$HOME/'~'}
    if [ "$current_path" = "~" ]; then
       echo $current_path
    else
       path_parent=${current_path%\/*}
       path_parent_short=`echo $path_parent | sed -r 's|/(.)[^/]*|/\1|g'`
       directory=${current_path##*\/}
       echo "$path_parent_short/$directory"
    fi
}

PS1='\u:$$(eval "sps") \$ '

which transforms /home/user/workspace/ocaml/project --> ~/w/o/project.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .