问题
We have a script that actually does git fetch; git checkout origin/<branch>
to deploy a certain feature. The reason why we do this is that we wan't to avoid local branches (it's a test server), so the script just fetch the latest changes and checkout into it, then reloads the server.
We also generate a log describing every deploy made, to bt sent by email to someone and archive. It's interesting that we send also the branch deployed, but the problem is when we do checkout origin/<branch>
, we're changing to a detached head. I read some answers with a similar question, but nothing so specific.
Is there a way to print what branch I am in this case (regardless user input, of course)?
回答1:
git symbolic-ref --short HEAD
should tell you what branch you are on, or print an error if you are not on a branch.
回答2:
Here's git nthlastcheckout
, it gets the exact string you used (or everything after its last space) for your nth last checkout from the reflog:
git config --global alias.nthlastcheckout '!nthlastcheckout'"() {
git reflog |
awk '\$3==\"checkout:\" {++n}
n=='\${1-1}' {print \$NF; exit}
END {exit n!='\${1-1}'}'
}; nthlastcheckout \"\$@\""
Examples:
$ git nthlastcheckout
master
$ git nthlastcheckout 2
v1.3.0^2
回答3:
The best solution for us, pointed by @SébastienDawans, was git show -s --pretty=%d HEAD
. The output is like remotes/origin/<branch name>
, so maybe a cleaning is required, but for our needs it's just fine.
来源:https://stackoverflow.com/questions/16971182/how-to-know-what-branch-i-am-on-git-when-checkout-origin-branch