Hacker News new | past | comments | ask | show | jobs | submit login

It's better to use a plumbing command for this sort of thing; git-completion.bash (http://git.kernel.org/?p=git/git.git;a=blob;f=contrib/comple...) has a thorough example. (The actual command called is 'git symbolic-ref HEAD'.)



That's definitely a lot more full-featured, but seems like overkill for what I was trying to do.

Had I known about `git symbolic-ref`, I might have used that instead of `git branch`. On the other hand, I would have needed to re-implement lots of what `git branch` does, such as detecting the difference between not being in a git repository and simply not being on a branch.

The interface of `git branch` seems stable enough that I doubt it will break this. If it does, it should take me no longer than 5 minutes to fix, since that's about how long it would take me to re-write the whole thing from scratch.

Is there any particular reason that using `git symbolic-ref` is better than `git branch` in this case, given that I want human-readable output, instead an unambiguous filesystem location?


Personally, I'd argue you do want to keep track of whether you are in a repo or not, since including that pipeline in your PS1 always forks three processes on every prompt. And if you're going to do that in your shell, it's good to have separate commands for each task.

For the case of not being on a branch, the output of 'git branch' is not very useful. I am currently using 'git name-rev --name-only HEAD', but the contrib script has an even fancier mechanism (via 'git describe') for coming up with something to display when HEAD isn't a symbolic ref.


Try this:

  export PS1='\w:$(__git_ps1 "%s")$ '
EDIT - here's mine btw:

  function parse_git_dirty {
    git diff --quiet HEAD &>/dev/null
    [[ $? == 1 ]] && echo "✎ " || echo "➜ "
  }
  function parse_git_branch {
    local branch=$(__git_ps1 "%s")
    [[ $branch ]] && echo "$branch$(parse_git_dirty)"
  }
  PS1='\u@\h $(parse_git_branch)\W $ '
If the branch has local changes it shows the pencil, in addition to the branch name. I'm still experimenting.


git-completion.bash has the added benefit of giving you tab-completion on git commands, and arguments to git commands.


It also shows the correct state of merge/rebase in the prompt as well. In many distributions, it's installed as /etc/bash_completion.d/git when you install git from a package management system, you just need to source /etc/bash_completion to get all the benefits.

The OP is an example of wheel reinvented, poorly.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: