5

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 1

4

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}%# '
2
  • 1
    This is good, but I've found a simpler method: git rev-parse --show-prefix to show exactly what I'm looking for. Commented 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. Commented Mar 17, 2014 at 8:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.