Seguimiento de todas las ramas remotas de git como ramas locales


El seguimiento de una sola rama remota como una rama local es bastante sencillo.

$ git checkout --track -b ${branch_name} origin/${branch_name}

Empujar todas las ramas locales hasta el remoto, creando nuevas ramas remotas según sea necesario también es fácil.

$ git push --all origin

Quiero hacer lo contrario. Si tengo X número de ramas remotas en una sola fuente:

$ git branch -r 
branch1
branch2
branch3
.
.
.

¿Puedo crear ramas de seguimiento locales para todas esas ramas remotas sin necesidad de crear manualmente cada una? Di algo como:

$ git checkout --track -b --all origin

He buscado en Google y rTMS, pero han llegado hasta aquí.

 146
Author: Janson, 2008-12-18

14 answers

Usando bash:

después de git 1.9.1
for i in `git branch -a | grep remote | grep -v HEAD | grep -v master`; do git branch --track ${i#remotes/origin/} $i; done

Créditos: Val Blant, elias, y Hugo

antes de git 1.9.1

Nota: el siguiente código si se usa en versiones posteriores de git (>v1.9.1) causa

  1. (bug) Todas las ramas creadas para rastrear master
  2. (annoyance) Todos los nombres de rama locales creados deben ir precedidos por origin/
for remote in `git branch -r `; do git branch --track $remote; done

Actualizar las ramas, suponiendo que no hay cambios en sus ramas de seguimiento locales:

for remote in `git branch -r `; do git checkout $remote ; git pull; done

Ignora las advertencias ambiguas de refname, git parece preferir la rama local como debería.

 84
Author: Otto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-25 18:47:48

La respuesta dada por Otto es buena, pero todas las ramas creadas tendrán "origin/" como inicio del nombre. Si solo desea que la última parte (después de la última /) sean sus nombres de rama resultantes, use esto:

for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done

También tiene el beneficio de no darte ninguna advertencia sobre referencias ambiguas.

 177
Author: tjmcewan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-12 11:25:38

Aquí está mi one-liner que uso (en un shell bash, probado con msysgit1.7.4):

Para copiar y pegar:

remote=origin ; for brname in `git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'`; do git branch --set-upstream-to $remote/$brname $brname; done

Para mayor legibilidad:

remote=origin ; // put here the name of the remote you want
for brname in `
    git branch -r | grep $remote | grep -v master | grep -v HEAD 
    | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'
`; do 
    git branch --set-upstream-to $remote/$brname $brname; 
done
  • solo seleccionará las ramas ascendentes del control remoto que especifique en la variable remote (puede ser 'origin' o el nombre que haya establecido para uno de los controles remotos de su repositorio Git actual).
  • extraerá el nombre de la rama: origin/a/Branch/Name => a/Branch/Name a través de la expresión awk.
  • Se establecerá el upstream branch through --set-upstream-to (or -u), no --track:
    La ventaja es que, si la rama ya existe, no fallará y no cambiará el origen de la rama, solo configurará la configuración branch.xxx.(remote|merge).

    branch.aBranchName.remote=origin
    branch.aBranchName.merge=refs/heads/a/Branch/Name
    

Ese comando creará ramas locales para todas las ramas ascendentes remotas, y establecerá su configuración remota y merge en esa rama remota.

 21
Author: VonC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:08

La mayoría de las respuestas aquí están complicando el análisis de la salida de git branch -r. Puede usar el siguiente bucle for para crear las ramas de seguimiento contra todas las ramas en el control remoto de esta manera.

Ejemplo

Digamos que tengo estas ramas remotas.

$ git branch -r
  origin/HEAD -> origin/master
  origin/development
  origin/integration
  origin/master
  origin/production
  origin/staging

Confirma que ya no estamos rastreando nada más que master, localmente:

$ git branch -l    # or using just git branch
* master

Puedes usar este liner para crear las ramas de seguimiento:

$ for i in $(git branch -r | grep -vE "HEAD|master"); do 
    git branch --track ${i#*/} $i; done
Branch development set up to track remote branch development from origin.
Branch integration set up to track remote branch integration from origin.
Branch production set up to track remote branch production from origin.
Branch staging set up to track remote branch staging from origin.

Ahora confirmar:

$ git branch
  development
  integration
* master
  production
  staging

Para eliminarlos:

$ git br -D production development integration staging 
Deleted branch production (was xxxxx).
Deleted branch development (was xxxxx).
Deleted branch integration (was xxxxx).
Deleted branch staging (was xxxxx).

Si usas el interruptor -vv a git branch puedes confirmar:

$ git br -vv
  development xxxxx [origin/development] commit log msg ....
  integration xxxxx [origin/integration] commit log msg ....
* master      xxxxx [origin/master] commit log msg ....
  production  xxxxx [origin/production] commit log msg ....
  staging     xxxxx [origin/staging] commit log msg ....

Desglose del bucle for

El bucle básicamente llama al comando git branch -r, filtrando cualquier rama HEAD o master en la salida usando grep -vE "HEAD|master". Para obtener los nombres de las ramas menos la subcadena origin/ usamos la manipulación de cadenas de Bash ${var#stringtoremove}. Esto eliminará la cadena "stringtoremove" de la variable $var. En nuestro caso estamos eliminando la string origin/ de la variable $i.

NOTA: Alternativamente puedes usar git checkout --track ... para hacer esto también:

$ for i in $(git branch -r | grep -vE "HEAD|master" | sed 's/^[ ]\+//'); do 
    git checkout --track $i; done

Pero no me importa particularmente este método, ya que te está cambiando entre las ramas mientras realiza un checkout. Cuando esté hecho, te dejará en la última rama que creó.

Referencias

 19
Author: slm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-01 18:43:27

Podrías escribir eso fácilmente, pero no se cuando sería valioso. Esas ramas se quedarían muy rápidamente atrás, y tendrías que actualizarlas todo el tiempo.

Las ramas remotas se mantendrán actualizadas automáticamente, por lo que es más fácil crear la rama local en el punto donde realmente desea trabajar en ella.

 12
Author: Dustin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-18 20:48:39
for i in `git branch -a | grep remote`; do git branch --track ${i#remotes/origin/} $i; done
 8
Author: Val Blant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-07 21:14:17

Sin ningún script (en un directorio vacío):

$ git clone --bare repo_url .git
$ git config core.bare false
$ git checkout

Después de eso, todas las ramas remotas serán vistas como locales.


Original (en ruso).

 4
Author: alexander barakin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-13 12:53:25
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master`; do  git branch --track ${branch##*/} $branch; done

Use esto y no tendrá una advertencia como: refname 'origin/dev' es ambiguo

 3
Author: bruziuz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-21 05:17:02

Si desea usar powershell y su control remoto se llama origin. Entonces esto funciona.

git fetch    
git branch -r  | %{$_ -replace "  origin/"} | %{git branch --track $_ "origin/$_"}
 3
Author: BigMiner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-24 15:20:26

Aquí está mi solución del comando BASH refiriéndose por @tjmcewan:

for remote in `git branch -r | grep -v /HEAD `; do git branch --track ${remote/"origin/"/""}; done

Mi objetivo es resolver el problema de que todas las ramas creadas tendrán " origin/"como inicio del nombre, porque probé que las variables remote remote todavía incluyen"origin/":

for remote in `git branch -r | grep -v /HEAD`; do echo $remote ; done
 3
Author: Nick Tsai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 08:17:49

Para hacer lo mismo que la respuesta de tjmcewan pero en Windows, llame a esto desde un archivo batch :

for /f "delims=" %%r in ('git branch -r ^| grep -v master') do git checkout --track %%r

O esto desde la línea de comandos :

for /f "delims=" %r in ('git branch -r ^| grep -v master') do git checkout --track %r
 2
Author: Hugo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:35

En caso de que ya tenga algunas ramas comprobadas y desee

  • echa un vistazo a todas las ramas restantes desde el control remoto
  • asegúrese de que todas las ramas locales rastrean las ramas remotas

Puede usar el siguiente script compatible con bash y zsh:

git branch -r | while read b; do if git branch | grep -q " ${b##*/}$"; then git branch --set-upstream ${b##*/} $b; else git branch --track ${b##*/} $b; fi; done
 0
Author: simonair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-26 10:19:55
for rembranch in `git remote update 2>&1 > /dev/null ; git branch -r|egrep -wv "HEAD|master"`
do 
    git checkout --track -b `echo $rembranch|awk -F\/ '{print $2}'` $rembranch; 
done

Explicación:

Línea 1: 'git branch-r' (seguido de 'git remote update' para actualizar la información sobre los cambios a remote) lista todas las ramas remotas; 'egrep-vw' se usa para golpear las entradas que tienen HEAD y master en el resultado.

Línea 3: Rastrea la rama remota nombrada mientras la revisas localmente. Se usa un awk simple para evitar que 'origin /' sea el sufijo de las ramas locales.

 0
Author: ksvrgh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-15 11:57:55

Usando bash, Si desea obtener todas las ramas:

for remote in `git branch -r`; do git checkout $(echo $remote | cut -d'/' -f 2); done

Es importante tener en cuenta que cuando haces un fetch que trae nuevas ramas de seguimiento remoto, no tienes automáticamente copias locales editables de ellas.

 0
Author: Jason Chen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 01:05:36