Reputation: 12273
I sometimes want to use the current branch name to use in git commands. For example
git push origin feature/really-long-branch-name
Is there a git command that will give just the branch name so I can do something like the following?
git push origin current_branch
There is git rev-parse --abbrev-ref HEAD
but that's exactly useful in this case. Setting a default branch isn't that helpful either since the branch name changes often. Changing the default behavior of git push
isn't what I'm looking for either since it still means having to type in the full branch name the first time I push
.
Edit:
Moderators, this question is not a dupe so please do not close for that reason. Please read the bolded part of my question carefully.
Upvotes: 24
Views: 15811
Reputation: 84343
--show-current
FlagWhile this answer from 2013 has stood the test of time, Git learned a new git-branch flag back in 2019 that makes this much easier. In commit 3710f60a80, git-branch learned a new flag for showing the current branch without requiring users to parse the list of branches or refs themselves. You can invoke it like so:
$ git branch --show-current
main
The other methods below continue to work, but this should now be the go-to solution for Git release versions >= v2.22.0.
There are a number of ways to get the name of the current branch. The most canonical is to read the symbolic ref for HEAD using git-symbolic-ref(1). For example, assuming you are on the master branch:
$ git symbolic-ref HEAD | sed 's!refs\/heads\/!!'
master
However you parse it, you can use the symbolic name in another command by invoking your shell's command substitution. For example, in Bash:
$ git log -n1 $(git rev-parse --abbrev-ref HEAD)
There's no reason you couldn't use this trick with push or other commands, if you choose.
If you're only interested in pushing the current branch to a remote branch with the same name, and aren't parsing the refs for some other reason, then you'd be better off using Git's push.default option described here and here. For example:
git config push.default current
Upvotes: 23
Reputation: 539
In the case of git push you can use HEAD.
The documentation states
git push origin HEAD
A handy way to push the current branch to the same name on the remote.
For cases where you can't use HEAD I would create an alias for it. I am only familiar with the mac environment, this solution is for that platform but I am sure there are ways to do the same on Windows.
In your ~/.bash_profile create this alias
alias current_branch="git rev-parse --abbrev-ref HEAD"
You can then use it in your git commands by doing
git push origin `current_branch`
Upvotes: 5