3 ms·
You might want to use `git rev-parse --abbrev-ref HEAD` or `git name-rev --name-only HEAD` instead of `git branch`. Plumbing commands (such as rev-parse or name
by sirn 5y ago
You might want to use `git rev-parse --abbrev-ref HEAD` or `git name-rev --name-only HEAD` instead of `git branch`. Plumbing commands (such as rev-parse or name-ref) are generally more interface-stable to use in a script than porcelain commands (such as git branch) which are designed for interactive use where output may change depending on user environment and configuration.
- MichaelMoser123 5y agomakes sense. thanks!
- NegativeLatency 5y agoI’ve heard this advice given before and initially followed it but ‘git branch’ and parsing the output works in a few cases (I don’t recall what they are at this time) that less hackey approaches don’t.
- sirn 5y agoI think that might be `git symbolic-ref` which doesn't work in detached HEAD state (e.g. when checking out a commit) whereas `git rev-parse --abbrev-ref` will print "HEAD". On the other hand, `git name-rev` will try to find the nearest named ref (including tags) and how far HEAD is from that named ref (e.g. master~1). Internally, symbolic-ref resolve the ref in the same way as git branch, just without handling detached HEAD. __git_ps1 use a combination of rev-parse, symbolic-ref and git describe to provide a more interesting output for displaying state of the working directory. To have the similar output for detached HEAD as git-status (e.g. "HEAD detached at fa0c4e1") then probably `git rev-parse --abbrev-rev` and `git rev-parse --short` should be used together. Unfortunately, while rev-parse can print multiple output in a single command, abbrev-rev and short cannot be used together. In such case, parsing `git status` might indeed be more suitable as it spawn only one executable instead of two. Some porcelain commands do have --porcelain flag to ensure the stability of the interface, though (e.g. `git status --porcelain=v1`).