If my pwd is ~/repos/blog/app/views/, I'd like to show only blog/app/views in the prompt i.e. I want to show only the project root. Project root is the parent directory of .git directory. Is there a way I can achieve this?
1 Answer
You can execute arbitrary code to display the prompt if you set the prompt_subst option. You don't need to look up the .git directory every time a prompt is displayed: in practice, it's enough to update a variable on every current directory change, in the chpwd hook, and use that variable in your prompt.
setopt prompt_subst
chpwd () {
  git_root=$PWD
  while [[ $git_root != / && ! -e $git_root/.git ]]; do
    git_root=$git_root:h
  done
  if [[ $git_root = / ]]; then
    unset git_root
    prompt_short_dir=%~
  else
    prompt_short_dir=${PWD#$git_root/}
  fi
}
chpwd
PS1='${prompt_short_dir}%# '
- 
        1This is good, but I've found a simpler method:git rev-parse --show-prefixto show exactly what I'm looking for.Abdulsattar Mohammed– Abdulsattar Mohammed2014-03-17 06:30:28 +00:00Commented Mar 17, 2014 at 6:30
- 
        @asattar That's another possibility, yes. I prefer to avoid calling external commands, but if you always work on a reasonably fast machine, that's not a concern.Gilles 'SO- stop being evil'– Gilles 'SO- stop being evil'2014-03-17 08:20:01 +00:00Commented Mar 17, 2014 at 8:20
