Agregar git branch en el símbolo del sistema de Bash


Intenté agregar la rama git en la que estoy trabajando actualmente (checked-out) en el prompt de bash sin éxito.. ( mientras mantengo mi ruta actual que muestra el archivo de active directory/ intacto) Tengo una .archivo bashrc en mi casa, pero también vi a mucha gente mencionar el.archivo de perfil..

Author: George Katsanos, 2013-04-08

10 answers

Tenga en cuenta que este tipo de solicitud ahora se administra mediante contrib / completion/git-prompt.sh y su variable __git_ps1_branch_name.

  • Copie este archivo en algún lugar (por ejemplo, ~/.git-prompt.sh).
  • Añade la siguiente línea a tu .bashrc/.zshrc:
  source ~/.git-prompt.sh
  • Cambie su PS1 para llamar a __git_ps1 como sustitución de comandos:
  Bash: 
  PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
  ZSH:  
  setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

Pero tenga en cuenta que solo git 1.9.3 (mayo de 2014) o posterior le permite de forma segura mostrar eso nombre de la sucursal (!)

Ver commit 8976500 por Richard Hansen (richardhansen):

Tanto bash como zsh someten el valor de PS1 a expansión de parámetros, sustitución de órdenes , y expansión aritmética.

En lugar de incluir el nombre de rama sin formato en PS1 cuando se ejecuta en dos o modo de tres argumentos, construir PS1 para hacer referencia a una variable que contiene el nombre de la rama.

Porque las conchas no expansión recursiva, esto evita la ejecución de código arbitrario por nombres de rama especialmente diseñados como

'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.

¿Qué mente tortuosa nombraría una rama como esa? ;) (Junto a una madre como en xkcd )


Still_dreaming_1 informes en los comentarios:

Esto parece funcionar muy bien si desea un indicador de color con xterm (en mi .bashrc):

PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\03‌​3[01;34m\]\w\[\033[00m\]$(__git_ps1)\$ ' 

Todo es de un color diferente, incluyendo el Sucursal.

En Linux Mint 17.3 Cinnamon 64-bit:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' 
 138
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:55:09

Siga los siguientes pasos: (Linux)

Edite el archivo ~/.bashrc, para introducir las siguientes líneas al final (En el caso de Mac, el archivo sería ~/.bash_profile)

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

Ahora, inicie la nueva ventana de terminal e intente ingresar a cualquier git-repo. Se mostrará la rama actual, con el prompt.

4 Más información - MAC/Linux

 46
Author: parasrish,
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-02-05 07:27:31

1-Si usted no tiene bash-completion... : sudo apt-get install bash-completion

2-Edita tu .bashrc file and check (or add) :

if [ -f /etc/bash_completion ]; then
  . /etc/bash_completion
fi

3- ... antes de la línea de solicitud: export PS1='$(__git_ps1) \w\$ '
(__git_ps1 mostrará tu rama git)

4 - do source .bashrc

EDITAR:

Otras lecturas: No Reinventes la Rueda

 30
Author: Eric Lavoie,
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-02 14:22:51

Así es como configuré el prompt para mostrar el estado de Git:

Obtener el script git-prompt:

curl -o ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

Y personalizar su mensaje añadiendo el siguiente código en su .archivo bashrc:

# Load Git functions
source ~/.git-prompt.sh

# Syntactic sugar for ANSI escape sequences
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Prompt variables
PROMPT_BEFORE="$txtcyn\u@\h $txtwht\w$txtrst"
PROMPT_AFTER="\\n\\\$ "

# Prompt command
PROMPT_COMMAND='__git_ps1 "$PROMPT_BEFORE" "$PROMPT_AFTER"'

# Git prompt features (read ~/.git-prompt.sh for reference)
export GIT_PS1_SHOWDIRTYSTATE="true"
export GIT_PS1_SHOWSTASHSTATE="true"
export GIT_PS1_SHOWUNTRACKEDFILES="true"
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS="true"

Si desea obtener más información, puede obtener todos los archivos de puntos aquí: https://github.com/jamming/dotfiles

 19
Author: jamming,
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-03-08 22:20:11

Para mac, esto funciona muy bien: http://martinfitzpatrick.name/article/add-git-branch-name-to-terminal-prompt-mac/:

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
 6
Author: Mike 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
2015-12-24 09:26:22
vim ~/.bash

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $"

Para reflejar los últimos cambios ejecute el siguiente comando

source ~/.bashrc

Salida: -

chandrakant@NDL41104 ~/Chandrakant/CodeBase/LaravelApp (development) $
 1
Author: Chandrakant Ganji,
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-04-24 13:56:33

Si utilizas la concha de pescado es bastante sencillo. fish es una concha interactiva que viene con muchas golosinas. Puede instalarlo usando apt-get.

sudo apt-get install fish

Luego puede cambiar la configuración del indicador usando

> fish_config 
Web config started at 'http://localhost:8001/'. Hit enter to stop.
Created new window in existing browser session.

Ahora vaya a http://localhost:8001/ abra la pestaña de solicitud y elija la opción classic + git

introduzca la descripción de la imagen aquí

Ahora haga clic en el botón usar solicitud y listo.

 0
Author: Shasak,
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-05-23 08:32:25
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(parse_git_branch)\n\$ '
 0
Author: xyz,
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-02-15 11:56:24

Sigue los siguientes pasos para mostrar el nombre de la rama de tu repositorio GIT en la terminal ubuntu:

Paso 1: abra la terminal y edite .bashrc usando el siguiente comando.

Vi .bashrc

Paso 2: añadir la siguiente línea al final de la .archivo bashrc:

parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

Paso 3: fuente .bashrc en el directorio raíz (home) haciendo:

/ rootfolder:~$ source .bashrc

Step4: Reinicie y abra el terminal y comprueba el cmd. Navega a la ruta de tu directorio Git repo y listo. :)

 0
Author: BinDev,
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-04-19 07:55:40

He probado un pequeño script en python que va en una carpeta bin.... archivo 'gitprompt'

#!/usr/bin/env python
import subprocess, os
s = os.path.join(os.getcwd(), '.git')
def cut(cmd):
    ret=''
    half=0
    record = False
    for c in cmd:
        if c == "\n":
            if not (record):
                pass
            else:
                break
        if (record) and c!="\n":
            ret = ret + c
        if c=='*':
            half=0.5
        if c==' ':
            if half == 0.5:
                half = 1
        if half == 1:
            record = True
    return ret
if (os.path.isdir(s)):
    out = subprocess.check_output("git branch",shell=True)
    print cut(out)
else:
    print "-"

Hacerlo ejecutable y cosas

Luego ajuste el indicador bash en consecuencia como:

\u:\w--[$(gitprompt)] \$ 
 -1
Author: Love_for_CODE,
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-07-04 18:58:35