Capaz de empujar a todos los controles remotos git con el comando único?


Respuestas:


253

Para empujar todas las ramas a todos los controles remotos:

git remote | xargs -L1 git push --all

O si desea enviar una rama específica a todos los controles remotos:

Reemplace mastercon la rama que desea empujar.

git remote | xargs -L1 -I R git push R master

(Bonificación) Para hacer un alias git para el comando:

git config --global alias.pushall '!git remote | xargs -L1 git push --all'

La ejecución git pushallahora empujará todas las ramas a todos los controles remotos.


1
Muy buena y simple solución. Por cierto, puede usar xargs -l en lugar de -L 1, la opción -l es la misma que -L 1. Además, a veces agrego --todos al git push. git remoto | xargs -l git push --todos
Tony

2
Me meto xargs: illegal option -- len OSX. Lo descubriste, lo necesitasgit remote | xargs -L1 git push
balupton

44
Git te permite convertir esa llamada en un comando personalizado. Simplemente póngalo en un archivo que 1) está en su ruta, 2) tiene permisos de ejecución y 3) llamado "git- [nombre personalizado]" (por ejemplo, git-foo, git-push-all) y obtendrá ser capaz de escribir simplemente "git [nombre personalizado]" (por ejemplo, git foo, git push-all).
Andrew Martin

2
@ Tony en Ubuntu, man xargsdice que la opción -lestá en desuso ya que no está en la especificación POISX.
wjandrea

2
@kyb En la sintaxis de alias git, !significa que lo siguiente no es un comando git interno, sino un comando de shell externo.
débil

285

Cree un allcontrol remoto con varias URL de repositorio a su nombre:

git remote add all origin-host:path/proj.git
git remote set-url --add all nodester-host:path/proj.git
git remote set-url --add all duostack-host:path/proj.git

Entonces solo git push all --all.


Así es como se ve en .git/config:

  [remote "all"]
  url = origin-host:path/proj.git
  url = nodester-host:path/proj.git
  url = duostack-host:path/proj.git

55
Truco súper genial! La única desventaja es que no mueve las cabezas remotas. Necesitas correr git fetch --alljusto después de hacer tal empuje.
loco

8
El Sr. Torvalds (creador de Git) menciona que él utiliza este método, pero él afirma que es meramente por conveniencia y no ofrece ninguna ventaja técnica marc.info/?l=git&m=116231242118202&w=2 "Y al final, incluso un" git push all "que empuja a múltiples repositorios en realidad terminará conectándose una vez para cada repositorio, por lo que es realmente una abreviatura para hacer múltiples" git push "es. No hay una ventaja técnica real, solo una conveniencia".
Matt

14
Un problema con este enfoque es que debe agregar nuevas URL al allcontrol remoto a medida que estén disponibles, mientras git remote | xargs -L1 git push --allque recogerá automáticamente cualquier control remoto nuevo.
Raffi Khatchadourian

2
Consejo: para no tener que escribir allcada vez que envíe una confirmación, simplemente use "origen" en lugar de "todos":git remote set-url --add origin nodester-host:path/proj.git
Macabeus

olvidé configurar las URL de inserción; de lo contrario git push, no se actualizarán todas. respuesta actualizada en consecuencia
user3338098

88

Si desea presionar siempre a repo1, repo2 y repo3 pero siempre tira solo de repo1, configure el 'origen' remoto como

[remote "origin"]
    url = https://exampleuser@example.com/path/to/repo1
    pushurl = https://exampleuser@example.com/path/to/repo1
    pushurl = https://exampleuser@example.com/path/to/repo2
    pushurl = https://exampleuser@example.com/path/to/repo3
    fetch = +refs/heads/*:refs/remotes/origin/*

Configurar en la línea de comando:

$ git remote add origin https://exampleuser@example.com/path/to/repo1
$ git remote set-url --push --add origin https://exampleuser@example.com/path/to/repo1
$ git remote set-url --push --add origin https://exampleuser@example.com/path/to/repo2
$ git remote set-url --push --add origin https://exampleuser@example.com/path/to/repo3

Si solo desea extraer repo1pero presionar hacia repo1y repo2 para una rama específicaspecialBranch :

[remote "origin"]
    url = ssh://git@aaa.xxx.com:7999/yyy/repo1.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    ...
[remote "specialRemote"]
    url = ssh://git@aaa.xxx.com:7999/yyy/repo1.git
    pushurl = ssh://git@aaa.xxx.com:7999/yyy/repo1.git
    pushurl = ssh://git@aaa.xxx.com:7999/yyy/repo2.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    ...
[branch "specialBranch"]
    remote = origin
    pushRemote = specialRemote
    ...

Ver https://git-scm.com/docs/git-config#git-config-branchltnamegtremote .


44
No estoy seguro de por qué esto no tiene más votos. En realidad, esto es realmente conveniente porque le permite hacer un git pushsin ningún argumento.
Husky

1
¡Vota por mí, por favor!
Meng Lu

1
Esto me parece una forma más apropiada de hacer esto. Debería haber tenido los votos más altos.
Ahmad

Es muy útil ¿Es posible limitar pushurl solo a la rama maestra?
fbucek

17

Como alternativa a la CLI para editar el archivo .git / config, puede usar los siguientes comandos:

# git remote add all origin-host:path/proj.git
# git remote set-url --add all nodester-host:path/proj.git
# git remote set-url --add all duostack-host:path/proj.git

Lo mismo git push all --allfunciona aquí también.

Has logrado lo mismo que la respuesta n. ° 1. Acaba de hacerlo con la línea de comandos en lugar de la edición sin formato del archivo de configuración.


2

Escribí una función bash corta para enviar muchos controles remotos en una sola llamada. Puede especificar un solo control remoto como parámetro, múltiples controles remotos separados por espacios o no especificar ninguno para que se transfiera a todos los controles remotos.

Esto se puede agregar a su .bashrc o .bash_profile.

function GitPush {
  REMOTES=$@

  # If no remotes were passed in, push to all remotes.
  if [[ -z "$REMOTES" ]]; then
    REM=`git remote`

    # Break the remotes into an array
    REMOTES=$(echo $REM | tr " " "\n")
  fi

  # Iterate through the array, pushing to each remote
  for R in $REMOTES; do
    echo "Pushing to $R..."
    git push $R
  done
}

Ejemplo: supongamos que su repositorio tiene 3 controles remotos: rem1, rem2 y rem3.

# Pushes to rem1
GitPush rem1

# Pushes to rem1 and rem2
GitPush rem1 rem2

# Pushes to rem1, rem2 and rem3
GitPush

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.