¿Hay una mejor manera de averiguar si existe una rama local de git?


Estoy usando el siguiente comando para averiguar si existe una rama de git local con branch-name en mi repositorio. ¿Es correcto? Hay una manera mejor?

Tenga en cuenta que estoy haciendo esto dentro de un script. Por esta razón me gustaría alejarme de los comandos de porcelana si es posible.

git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists. 

Actualización

Resulta que hay otra manera. Gracias @jhuynh.

git rev-parse --verify <branch-name>
# $? == 0 means local branch with name <branch-name> exists.
Author: stkent, 2011-03-02

13 answers

Por lo que sé, esa es la mejor manera de hacerlo en un guión. No estoy seguro de que haya mucho más que agregar a eso, pero también podría haber una respuesta que solo diga "Ese comando hace todo lo que quieres":)

Lo único de lo que debes tener cuidado es que los nombres de las ramas pueden tener caracteres sorprendentes, por lo que es posible que quieras citar <branch-name>.

 40
Author: Mark Longair,
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-06-12 13:32:18

Cuando busco 'git check if branch exists' en un motor de búsqueda, esta página es la primera que veo.

Consigo lo que quiero, pero me gustaría proporcionar una respuesta actualizada ya que el post original era de 2011.

git rev-parse --verify <branch_name>

Esto es esencialmente lo mismo que la respuesta aceptada, pero no es necesario escribir "refs/heads/"

 82
Author: jhuynh,
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-02-27 23:24:13

Casi ahí.

Simplemente omite --verify y --quiet y obtienes el hash si la rama existe o nada si no lo hace.

Asígnelo a una variable y compruebe si hay una cadena vacía.

exists=`git show-ref refs/heads/<branch-name>`
if [ -n "$exists" ]; then
    echo 'branch exists!'
fi
 24
Author: Martijn,
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-06-11 18:52:59

Creo que puedes usar git show-branch aquí.

$ git show-branch --list
  [master] test
* [testbranch] test
$ git show-branch testbranch
[testbranch] test
$ echo $?
0
$ git show-branch nonexistantbranch
fatal: bad sha1 reference nonexistantbranch
$ echo $?
128

Entonces,$? = = 0 indicaría que la rama existe y no tienes que cavar en la fontanería de refs / heads / en absoluto. Mientras no pase -r a show-branch, solo operará en ramas locales.

 14
Author: Mark Drago,
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
2011-03-02 13:30:49

Recomiendo git show-ref --quiet refs/heads/$name.

  • --quiet significa que no hay salida, lo cual es bueno porque entonces puede verificar limpiamente el estado de salida.

  • refs/heads/$name límites a las ramas locales y coincidencias nombres completos (de lo contrario dev coincidiría develop)

Uso en un script:

if git show-ref --quiet refs/heads/develop; then
    echo develop branch exists
fi
 10
Author: Razzi Abuissa,
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-09-18 21:40:02

Vamos a llamarlo git is_localbranch (necesita agregar alias en .gitconfig).

Uso:

$ git is_localbranch BRANCH

Fuente:

git branch | grep -w $1 > /dev/null
if [ $? = 0 ]
then
  echo "branch exists"
fi
 2
Author: Zlatan,
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-01-12 10:31:03

En windows batch script es un poco diferente,

git rev-parse --verify <branch>

if %ERRORLEVEL% == 0  (
    echo "Yes"
) else (
    echo "No"
)
 2
Author: pinkal vansia,
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-10 11:06:48

El resultado de la revisión de mi 'Edición Sugerida' a la 'Actualización' sobre la pregunta inicial fue 'Debería haber sido escrito como un comentario o una respuesta', así que lo estoy publicando aquí:

El another way propuesto no solo verificará las ramas sino cualquier referencia con dicho nombre @jhuynh.

git rev-parse --verify <reference-name>
# $? == 0 means reference with <reference-name> exists.

Problema con una' Actualización ' sobre quiestion inicial explicado:

Vamos a asumir y comprobar que ' maestro.000 ' es solo una etiqueta, dicha rama local no existe, grep devuelve una entrada que es una etiqueta. Todavía rev-parse devolverá 0 si existe referencia, incluso si dicha rama local no existe. Esta es una coincidencia falsa, exactamente como lo menciona @paul-s

$ git show-ref |grep master.000

f0686b8c16401be87e72f9466083d29295b86f4a refs/tags/master.000
$ git rev-parse --verify master.000
f0686b8c16401be87e72f9466083d29295b86f4a
$ echo $?
0
 0
Author: Przemek108,
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:55:07

Quería usarlo el navegador, así que hice una pequeña aplicación que te permite verificar la validez del nombre de tu sucursal. Está respaldado por Git, así que sabes lo que vas a conseguir.

Https://branch-checker.herokuapp.com/validate?branch=not//valid

 0
Author: obfk,
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-10-15 16:08:45

Para usar en un script:

git show-ref -q --heads <branch-name>

Esto saldrá 0 si y solo si <branch-name> existe como una rama local.

Ejemplo:

if git show-ref -q --heads <branch-name>; then
   echo 'Branch exists'
fi
 0
Author: Tom Hale,
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-14 15:18:54

Si puede incluir grep.

git branch | grep -q <branch>
 -1
Author: Daniel Vikström,
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-12-09 12:13:49

Para usar en un script, recomiendo el siguiente comando:

git ls-remote --heads <repo_url> "<branch_name>" | wc -l

Tenga en cuenta que <repo_url> puede ser simplemente un "."para especificar el repositorio local si se encuentra dentro de su estructura de directorios, la ruta a un repositorio local o la dirección de un repositorio remoto.

El comando devuelve un 0 si el <branch_name> no está presente de 1 si está presente.

 -1
Author: David,
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-10-26 06:07:38

$ git branch --lista $branch_name | grep $branch_name a continuación, compruebe que el valor devuelto es 0 o 1.

 -1
Author: Howell ZHU,
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-12-18 05:05:03