Comprobar si el directorio actual es un repositorio Git


Estoy escribiendo una serie de scripts para la administración de Git en zsh.

¿Cómo puedo comprobar si el directorio actual es un repositorio Git? (Cuando no estoy en un repositorio Git, no quiero ejecutar un montón de comandos y obtener un montón de fatal: Not a git repository respuestas).

 127
Author: nyuszika7h, 2010-02-02

12 answers

Copiado del archivo de finalización de bash la siguiente es una forma ingenua de hacerlo

# Copyright (C) 2006,2007 Shawn O. Pearce <[email protected]>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.

if [ -d .git ]; then
  echo .git;
else
  git rev-parse --git-dir 2> /dev/null;
fi;

Puede envolver eso en una función o usarlo en un script.

Condensado en una condición de una línea adecuada para bash o zsh

[ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1
 113
Author: jabbie,
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-08-08 02:09:46

Puedes usar:

git rev-parse --is-inside-work-tree

Que imprimirá 'true' si estás en un árbol de trabajo de repositorios de git.

Tenga en cuenta que todavía devuelve la salida a STDERR si está fuera de un repositorio git (y no imprime 'false').

Tomado de esta respuesta: https://stackoverflow.com/a/2044714/12983

 66
Author: TM.,
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:36

Use git rev-parse {git-dir

if git rev-parse --git-dir > /dev/null 2>&1; then
  : # This is a valid git repository (but the current working
    # directory may not be the top level.
    # Check the output of the git rev-parse command if you care)
else
  : # this is not a git repository
fi
 34
Author: William Pursell,
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
2010-02-02 15:48:04

O podrías hacer esto:

inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"

if [ "$inside_git_repo" ]; then
  echo "inside git repo"
else
  echo "not in git repo"
fi
 11
Author: Alex Cory,
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-06-29 01:25:17

No estoy seguro de si hay una forma públicamente accesible/documentada de hacer esto (hay algunas funciones internas de git que puedes usar/abusar en la propia fuente de git)

Podrías hacer algo como;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi
 5
Author: James,
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
2010-02-01 21:59:06

Otra solución es comprobar el código de salida del comando.

git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1

Esto imprimirá 1 si estás en una carpeta de repositorio git.

 5
Author: ,
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-12-14 10:14:16

Una opción muy rápida es http://vc.gerg.ca/hg/vcprompt / .. multi-VC, en C, no hay dependencias aparte de sí mismo.

 3
Author: peritus,
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
2010-02-01 21:50:58

¿Ya ha comprobado funciones en la distribución zsh? Ver esta entrada de blog acerca de vcs_info en zsh.

ACTUALIZACIÓN :

Parece que el enlace original fue eliminado y el autor cambió su dominio principal. Revisé Google y creo que actualmente el post enlazado tiene el mismo contenido, pero no lo sé con seguridad (Fue hace mucho tiempo desde que revisé el enlace original).

 2
Author: MBO,
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-05-13 18:43:14

Esto funciona para mí. Todavía obtienes los errores, pero son bastante fáciles de suprimir. también funciona desde dentro de subcarpetas!

Git status > / dev / null 2>&1 && ¡hola Mundo!

Puede poner esto en una sentencia if then si necesita hacer más condicionalmente.

 1
Author: CharlesTWall3,
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-19 04:31:54

Puede agregar o reemplazar su PS PS1 en su zshrc con una o otra herramientas git-prompt. De esta manera puedes estar convenientemente informado de si estás en un repositorio git y el estado del repositorio está en.

 1
Author: jxqz,
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-10-25 04:45:59
! git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { 
  printf '%s\n\n' "GIT repository detected." && git status
}

El ! lo niega, por lo que incluso si ejecuta esto en un directorio que no es un repositorio de git, no le dará algunos errores fatales

El >/dev/null 2>&1 envía los mensajes a /dev/null ya que está justo después del estado de salida. Las {} son para las agrupaciones de comandos por lo que todos los comandos después de la || se ejecutará si el git rev-parse tuvo éxito ya que usamos a ! que negaba el estado de salida de git rev-parse. El printf es solo para imprimir algún mensaje y git status para imprimir el estado del repositorio.

Envuélvalo en una función o póngalo en un script. Espero que esto ayude

 0
Author: Jetchisel,
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-08-08 04:47:47

Véase también:

git rev-parse --is-inside-work-tree

(descubierto leyendo man git-rev-parse)

 -1
Author: beneroth,
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-04-04 21:42:37