In order to compare two branches easily, you have to use the “git diff” command and provide the branch names separated by dots. Using this command, Git will compare the tip of both branches (also called the HEAD) and display a “diff” recap that you can use to see modifications.
The "checkout" command can switch the currently active branch - but it can also be used to restore files.
The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1
. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.
Alternate solution could be:
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.
Added 11-06-2013
Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.
Does anyone see anything wrong with just asking Git to describe the branch you are on?
git rev-parse --symbolic-full-name --abbrev-ref HEAD
That can be used within $() and passed easily in Bash, Powershell, Perl, etc. It isn't fooled if you have several branches on the commit you are on, and if you currently aren't on a branch, it simply replies with "HEAD".
Alternatively, you can use
git symbolic-ref --short -q HEAD
Which will give you the same output, but it won't return anything at all if you are detached. This one is useful if you want an error when detached though, just remove the -q.
you can use
git name-rev --name-only HEAD
From this answer: https://stackoverflow.com/a/1418022/605356 :
$ git rev-parse --abbrev-ref HEAD
master
Apparently works with Git 1.6.3 or newer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With