4

I have multiple local branches on my computer without remote.

I would like to push all my local branches that are not tracking a remote (I have multiple remote, e.g. origin and upstream) to the same remote (e.g. backup) url. For backuping purpose.

How could I do this?

Solution can be direct Git command or a bash script for listing branches without remote (I have multiple remote names) and iterating over them to push them to the same remote.

Catree
  • 2,477
  • 1
  • 17
  • 24
  • Uh, for each branch in question you would say `git push `. For example, `git push origin branch1`. Can you explain what the hard part is? – matt Nov 26 '21 at 17:20
  • 1
    @matt I think they're looking for something that will push _all of them_, i.e. without having to manually type out each branch name. – IMSoP Nov 26 '21 at 17:28
  • @matt Exactly, I have lots of non tracked branches (e.g. for debugging purposes or unfinished features) and I would like to push **all** of them for backup purposes. – Catree Nov 26 '21 at 17:30
  • Probably my question fits more for a bash script. A combination of listing all local branches without remote (https://stackoverflow.com/a/31776247) + iterating over them. Unfortunately my knowledge of bash script is very poor. – Catree Nov 26 '21 at 17:43
  • Have you tried `git push --all -u`? – Ionuț G. Stan Nov 26 '21 at 17:43
  • Just push all the branches. It's unlikely that you are going to save much time or space due to commits that are reachable *only* from the local branches you are describing. – chepner Nov 26 '21 at 17:57
  • If this is a one-off problem, I would parse the output of `git branch -v -v` by grepping out the ones with a remote, e.g., `git branch -v -v | grep -v '\[[a-z]*/'` worked for me since my remotes all match `[a-z]*`. This is *not* a good solution for scripting, but for a one-off that's how I would approach it. – joanis Nov 26 '21 at 21:33
  • @IonuțG.Stan Woulnd't that also update the upstream for branches that already had an upstream? – joanis Nov 26 '21 at 21:35

1 Answers1

2

Probably my question fits more for a bash script.
A combination of listing all local branches without remote + iterating over them.

#!/bin/bash
while IFS= read -r aBranch ; do {  
  echo "Push ${aBranch} to backup";  
  git push backup "${aBranch}"
};
done < <(git branch --format '%(refname:short) %(upstream:short)' | awk '{if (!$2) print $1;}');
unset aBranch ;
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • pretty neat. I don't think you need `IFS` here though, it is simpler with `while read branch; do ... done < <(git branch --format '%(refname:short) %(upstream:short)'...) ` – Eugene Nov 27 '21 at 01:43