I wanted a $PWD shrinking for my $PROMPT with the following requirements:

  • $HOME is replaced by ~
  • All subpaths except the last one are replaced by their initial letters
  • Reasonably efficient

This is my attempt, with tests:


function shrinkpath()
  local dir="${1/#$HOME/~}"
  if [ $dir = "~" ]; then
    echo "~"
  local split=(${(s:/:)dir%/*})
  local prefix="/"
  if [ "$split[1]" = "~" ]; then
  local mid=$(for i ("$split[@]") ; do echo -n "${i:0:1}/" ; done)
  local last="${dir##*/}"
  echo "$prefix$mid$last"

echo "$(shrinkpath $HOME)"
echo "$(shrinkpath $HOME/foo)"
echo "$(shrinkpath $HOME/foo/bar/baz)"
echo "$(shrinkpath /)"
echo "$(shrinkpath /foo)"
echo "$(shrinkpath /foo/bar/baz)"



Seems to be doing the trick but I feel it could be smaller/simpler. In particular, my intuition tells me that I should be able to get away with a single check for "~" instead of two, and that I might be using too many intermediate variables. I am also not sure about whether there is a better way to do the "split by / and get the first letter of each subpath" part.


Your Answer

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

Browse other questions tagged or ask your own question.