Question

Usually when I push I use git push origin master which I usually read in my head as, push TO the remote origin FROM my local master. I'm making a script right now that needs to be used many people. Let's say we have a remote branch called Release 1.0. I want my script to automatically push the users branch to it's remote, no matter what the name of the branch is. So lets say we have a branch called experimentalBranch that is based off of Release 1.0. How can I always push a branch to it's remote, no matter the name? With my normal way it wouldn't work, as I specify the local branch name master.

I should add that I don't know the name of the remote either. Essentially I want to say "push my local branch to it's remote, whatever the local and remote may be."

Was it helpful?

Solution

This pushes to a given remote with the right branch name, whatever it is:

git push origin HEAD

Unfortunately you still need to know the remote name for this.

If you want something that works even without knowing the remote name, it's a bit more complicated. The best way I could find was this command, which prints the name of the remote tracking branch, including the name of the remote:

git rev-parse --abbrev-ref --symbolic-full-name @{u}

This outputs in the format remotename/branchname. From this you can extract the remote name using bash, for example:

refname=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})
IFS=/ read -a arr <<< "$refname"
remote=${arr[0]}
branch=${arr[1]}

And then you can push like this:

git push $remote $branch
# actually this should do as well:
# git push $remote HEAD

OTHER TIPS

The script you want:

current_branch=$(git rev-parse --abbrev-ref HEAD)
git push origin $current_branch

You can type those lines in at terminal, or put them in a file and run that file as a script.

If you want something nice like git push origin self at the terminal, put this in ~/.bashrc:

git()
{
  if [ "$1" == "push" ] && [ "$2" == origin ] && [ "$3" == "self" ]; then
    current_branch=$(git rev-parse --abbrev-ref HEAD)
    git push origin $current_branch
  else
    command git "$@"
  fi
}

You probably want this:

git config --global push.default current

After you have configured this, and you do:

git push foobar

It will basically be translated to:

git push foobar HEAD
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top