# Índice / Table of Contents / Table des Matières / Índice
1. [English](#english)
2. [Português](#português)
3. [Français](#français)
4. [Español](#español)
5. [Credits / Créditos / Crédits]
==========
## English
This document provides a detailed guide to using Git, explaining key commands and configurations necessary for effective version control. It covers local and remote repositories, branching, merging, stashing, rebasing, and more. The guide is ideal for beginners who want to understand Git and for advanced users who seek a comprehensive reference.
## Português
Este documento oferece um guia detalhado para utilizar o Git, explicando os comandos e configurações essenciais para um controle de versão eficiente. Abrange repositórios locais e remotos, criação de branches, merges, stash, rebase, e muito mais. Ideal tanto para iniciantes quanto para utilizadores avançados que buscam um guia completo.
## Français
Ce document offre un guide détaillé sur l'utilisation de Git, expliquant les commandes et configurations essentielles pour un contrôle de version efficace. Il couvre les dépôts locaux et distants, les branches, les fusions, le stash, le rebase, et bien plus. Idéal pour les débutants comme pour les utilisateurs avancés qui recherchent une référence complète.
## Español
Este documento proporciona una guía detallada para usar Git, explicando los comandos y configuraciones clave necesarios para un control de versiones efectivo. Cubre repositorios locales y remotos, ramas, fusiones, stashing, rebasing, y más. Ideal tanto para principiantes como para usuarios avanzados que buscan una referencia completa.
==========
## Créditos / Credits / Crédits
Este documento foi baseado no trabalho original de [Leonardo Comelli](https://gist.github.com/leocomelli), e as traduções foram feitas por [jsvenancio](https://github.com/jsvenancio).
-
-
Save jsvenancio/95a8e4829b31468df0488fb4fffa921b to your computer and use it in GitHub Desktop.
- Modified
- Staged (index)
- Committed
git helpgit help add
git help commit
git help <any_git_command>The GIT configurations are stored in the .gitconfig file, located in the user's directory (e.g., Windows: C:\Users\Documents and Settings\Leonardo, or *nix /home/leonardo).
Configurations made using the commands below will be included in this file.
git config --global user.name "Leonardo Comelli"git config --global user.email [email protected]git config --global core.editor vimgit config --global merge.tool vimdiffgit config --global core.excludesfile ~/.gitignoregit config --listThe file/directory names or file extensions listed in the .gitignore file will not be added to a repository. There are two types of .gitignore files:
-
Global: Typically stored in the user's OS directory. It contains the list of files/directories to be ignored by all repositories. The file doesn't need to be named .gitignore.
-
Per Repository: Stored in the repository's directory, containing the files/directories to be ignored only for that specific repository.
git initgit statusgit add my_file.txtgit add my_directorygit add .git add -f file_in_gitignore.txtgit commit my_file.txtgit commit my_file.txt my_other_file.txtgit commit my_file.txt -m "my commit message"git rm my_file.txtgit rm -r directorygit loggit log -p -2git log --statgit log --pretty=onelinegit log --pretty=format:"%h - %an, %ar : %s"%h: Abbreviated hash%an: Author's name%ar: Date%s: Comment
Refer to more formatting options in the Git Book.
git log -- <file_path>git log --summary -S<word> [<file_path>]git log --diff-filter=M -- <file_path><D>can be replaced by: Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), etc.
git log --author=usernamegit blame -L 12,22 my_file.txtUse this command before the file is added to the staging area:
git checkout -- my_file.txtUse this when the file has been added to the staging area:
git reset HEAD my_file.txtIf you see this output, the reset command didn't affect the working directory:
Unstaged changes after reset:
M my_file.txtgit checkout my_file.txtgit remote
git remote -vgit remote add origin [email protected]:leocomelli/curso-git.gitgit remote show origingit remote rename origin curso-gitgit remote rm curso-gitThe first push needs the remote repository name and branch:
git push -u origin masterSubsequent pushes:
git pushgit pullAutomerging my_file.txt
CONFLICT (content): Merge conflict in my_file.txt
Automatic merge failed; fix conflicts and then commit the result.
git branch -d bug-123git branchgit branch -vgit branch --mergedgit branch --no-mergedgit push origin bug-123git push origin bug-123:new-branchgit checkout -b bug-123 origin/bug-123git push origin :bug-123Performing a rebase between the bug-123 branch and master:
git checkout experiment
git rebase masterMore information and explanations about Rebasing.
To switch between branches, you usually need to commit your current changes before moving to another branch. If you need to switch without committing, you can create a stash. The stash acts like a temporary branch containing only uncommitted changes.
git stashgit stash listgit stash applygit stash apply stash@{2}Where 2 is the stash index.
git stash branch my_branchgit commit --amend -m "My new message"git rebase -i HEAD~3The text editor will open with lines representing the last three commits. Change pick to edit for the commits you want to modify, then amend the message with:
git commit --amend -m "New message"Apply changes with:
git rebase --continueNote: You can reorder or remove commits by modifying or deleting lines in the editor.
Follow the same steps as above, but mark the commits to be combined with squash.
git filter-branch --tree-filter 'rm -f passwords.txt' HEADThe bisect (binary search) is useful for finding a commit causing a bug or inconsistency between a series of commits.
git bisect startgit bisect badgit bisect good vs-1.1git bisect goodgit bisect badReturn to HEAD with:
git bisect resetFeel free to add more information or make corrections. Fork me!
- Modificado (modified);
- Preparado (staged/index)
- Consolidado (committed);
git helpgit help add
git help commit
git help <cualquier_comando_git>Las configuraciones de GIT se almacenan en el archivo .gitconfig, ubicado dentro del directorio del usuario del sistema operativo (Ej.: Windows: C:\Users\Documents and Settings\Leonardo o *nix /home/leonardo).
Las configuraciones realizadas con los comandos a continuación se incluirán en el archivo mencionado.
git config --global user.name "Leonardo Comelli"git config --global user.email [email protected]git config --global core.editor vimgit config --global merge.tool vimdiffgit config --global core.excludesfile ~/.gitignoregit config --listLos nombres de archivos/directorios o extensiones de archivos listados en .gitignore no se agregarán a un repositorio.
-
General: Normalmente se almacena en el directorio del usuario del sistema operativo. El archivo que contiene la lista de archivos/directorios a ignorar por todos los repositorios debe ser declarado como se mencionó antes. El archivo no necesariamente debe llamarse .gitignore.
-
Por repositorio: Debe almacenarse en el directorio del repositorio y debe contener la lista de archivos/directorios que deben ser ignorados solo para ese repositorio específico.
git initgit statusgit add mi_archivo.txtgit add mi_directoriogit add .git add -f archivo_en_gitignore.txtgit commit mi_archivo.txtgit commit mi_archivo.txt mi_otro_archivo.txtgit commit mi_archivo.txt -m "mi mensaje de commit"git rm mi_archivo.txtgit rm -r directoriogit loggit log -p -2git log --statgit log --pretty=onelinegit log --pretty=format:"%h - %an, %ar : %s"- %h: Abreviatura del hash;
- %an: Nombre del autor;
- %ar: Fecha;
- %s: Comentario.
Consulta más opciones de formato en el Git Book
git log -- <ruta_del_archivo>git blame -L 12,22 mi_archivo.txtEste comando debe utilizarse mientras el archivo no haya sido añadido al staging area.
git checkout -- mi_archivo.txtEste comando debe usarse cuando el archivo ya fue añadido al staging area.
git reset HEAD mi_archivo.txtSi aparece el resultado:
Unstaged changes after reset:
M mi_archivo.txt
El cambio del directorio se puede hacer con el comando:
git checkout mi_archivo.txtPosso continuar a tradução para espanhol por partes menores, garantindo que está completa e precisa. Aqui está a tradução desta parte:
git remote
git remote -vgit remote add origin [email protected]:leocomelli/curso-git.gitgit remote show origingit remote rename origin curso-gitgit remote rm curso-gitEl primer push de un repositorio debe incluir el nombre del repositorio remoto y la rama:
git push -u origin masterLos siguientes pushes no requieren esta información:
git pushgit pullgit fetchgit clone [email protected]:leocomelli/curso-git.gitgit tag vs-1.1git tag -a vs-1.1 -m "Mi versión 1.1"Para crear una etiqueta firmada, se necesita una clave privada (GNU Privacy Guard - GPG).
git tag -s vs-1.1 -m "Mi etiqueta firmada 1.1"git tag -a vs-1.2 9fceb02git push origin vs-1.2git push origin --tagsLa master es la rama principal de GIT.
El HEAD es un puntero especial que indica cuál es la rama actual. Por defecto, HEAD apunta a la rama principal, master.
git branch bug-123git checkout bug-123En este caso, el puntero principal HEAD está apuntando a la rama llamada bug-123.
git checkout -b bug-456git checkout mastergit merge bug-123Para realizar el merge, es necesario estar en la rama que recibirá los cambios. El merge puede ser automático o manual. El merge automático ocurre en archivos de texto sin cambios en las mismas líneas, mientras que el merge manual se realiza cuando hay cambios en las mismas líneas.
El mensaje que indica un merge manual será:
Automerging mi_archivo.txt
CONFLICT (content): Merge conflict in mi_archivo.txt
Automatic merge failed; fix conflicts and then commit the result.
git branch -d bug-123git branchgit branch -vgit branch --mergedgit branch --no-mergedgit push origin bug-123git push origin bug-123:nueva-ramagit checkout -b bug-123 origin/bug-123git push origin :bug-123Realizando un rebase entre la rama bug-123 y master:
git checkout experiment
git rebase masterMás información y explicaciones sobre el Rebasing.
Para alternar entre una rama y otra, es necesario hacer commit de los cambios actuales antes de cambiar de rama. Si es necesario realizar el cambio sin hacer el commit, se puede crear un stash. El stash actúa como una rama temporal que contiene solo los cambios aún no commitados.
git stashgit stash listgit stash applygit stash apply stash@{2}Donde 2 es el índice del stash deseado.
git stash branch mi_ramagit commit --amend -m "Mi nuevo mensaje"Modificando los últimos tres commits:
git rebase -i HEAD~3El editor de texto se abrirá con las líneas que representan los últimos tres commits.
pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added catfile
Cambia a edit para los commits que deseas modificar.
edit f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added catfile
Cierra el editor de texto.
Escribe el comando para cambiar el mensaje del commit marcado como edit:
git commit –amend -m “Nuevo mensaje”Aplica el cambio:
git rebase --continueAtención: Puedes cambiar el orden de los commits o eliminar uno modificando o eliminando líneas.
Siga los mismos pasos mencionados anteriormente, pero marque los commits que deben ser combinados con squash.
git filter-branch --tree-filter 'rm -f passwords.txt' HEADEl bisect (búsqueda binaria) es útil para encontrar un commit que está causando un error o una inconsistencia en una secuencia de commits.
git bisect startgit bisect badgit bisect good vs-1.1GIT navegará entre los commits para ayudar a identificar el commit problemático. Si el commit actual no tiene problemas, márcalo como bueno.
git bisect goodSi el commit tiene problemas, márcalo como malo.
git bisect badDespués de encontrar el commit problemático, para volver al HEAD usa:
git bisect resetSiéntete libre de añadir más información o realizar correcciones. ¡Haz un fork!
- Modifié (modified);
- Préparé (staged/index);
- Consolidé (committed);
git helpgit help add
git help commit
git help <n'importe quelle_commande_git>Les configurations GIT sont stockées dans le fichier .gitconfig, situé dans le répertoire utilisateur du système d'exploitation (ex.: Windows: C:\Users\Documents and Settings\Leonardo ou *nix /home/leonardo).
Les configurations effectuées via les commandes ci-dessous seront incluses dans le fichier mentionné.
git config --global user.name "Leonardo Comelli"git config --global user.email [email protected]git config --global core.editor vimgit config --global merge.tool vimdiffgit config --global core.excludesfile ~/.gitignoregit config --listLes noms de fichiers/répertoires ou extensions listés dans le fichier .gitignore ne seront pas ajoutés à un dépôt. Il existe deux fichiers .gitignore :
-
Global : Généralement stocké dans le répertoire utilisateur. Ce fichier contient la liste des fichiers/répertoires à ignorer pour tous les dépôts et n'a pas besoin de s'appeler .gitignore.
-
Par dépôt : Stocké dans le répertoire du dépôt, il contient la liste des fichiers/répertoires à ignorer uniquement pour ce dépôt spécifique.
git initgit statusgit add mon_fichier.txtgit add mon_repertoiregit add .git add -f fichier_dans_gitignore.txtgit commit mon_fichier.txtgit commit mon_fichier.txt mon_autre_fichier.txtgit commit mon_fichier.txt -m "mon message de commit"git rm mon_fichier.txtgit rm -r repertoiregit loggit log -p -2Afficher un résumé de l'historique (hash complet, auteur, date, commentaire, et nombre de modifications (+/-))
git log --statgit log --pretty=onelinegit log --pretty=format:"%h - %an, %ar : %s"%h: Abréviation du hash%an: Nom de l'auteur%ar: Date%s: Commentaire
Consultez les autres options de formatage dans le Git Book.
git log -- <chemin_du_fichier>git log --summary -S<mot> [<chemin_du_fichier>]git log --diff-filter=M -- <chemin_du_fichier><D>peut être remplacé par: Ajouté (A), Copié (C), Supprimé (D), Modifié (M), Renommé (R), entre autres.
git log --author=utilisateurgit blame -L 12,22 mon_fichier.txtCe command doit être utilisé tant que le fichier n'a pas été ajouté à la zone de staging.
git checkout -- mon_fichier.txtCe command doit être utilisé lorsque le fichier a déjà été ajouté à la zone de staging.
git reset HEAD mon_fichier.txtSi le résultat ci-dessous apparaît, la commande reset n'a pas modifié le répertoire de travail :
Unstaged changes after reset:
M mon_fichier.txt
Le changement du répertoire peut être réalisé avec la commande suivante :
git checkout mon_fichier.txtgit remote
git remote -vgit remote add origin [email protected]:leocomelli/curso-git.gitgit remote show origingit remote rename origin cours-gitgit remote rm cours-gitLe premier push d'un dépôt doit contenir le nom du dépôt distant et la branche :
git push -u origin masterLes push suivants ne nécessitent pas cette information :
git pushgit pullgit fetchgit clone [email protected]:leocomelli/curso-git.gitgit tag vs-1.1git tag -a vs-1.1 -m "Ma version 1.1"Pour créer une tag signée, une clé privée (GNU Privacy Guard - GPG) est nécessaire :
git tag -s vs-1.1 -m "Ma tag signée 1.1"git tag -a vs-1.2 9fceb02git push origin vs-1.2git push origin --tagsLa branche master est la branche principale de GIT.
Le HEAD est un pointeur spécial qui indique la branche actuelle. Par défaut, HEAD pointe vers la branche principale, master.
git branch bug-123git checkout bug-123Dans ce cas, le pointeur principal HEAD pointe vers la branche appelée bug-123.
git checkout -b bug-456git checkout mastergit merge bug-123Pour effectuer le merge, il est nécessaire d'être sur la branche qui recevra les modifications. Le merge peut être automatique ou manuel. Le merge automatique se fait sur des fichiers texte sans modifications aux mêmes lignes, tandis que le merge manuel est requis lorsque des modifications existent sur les mêmes lignes.
Le message indiquant un merge manuel sera :
Automerging mon_fichier.txt
CONFLICT (content): Merge conflict in mon_fichier.txt
Automatic merge failed; fix conflicts and then commit the result.
git branch -d bug-123git branchgit branch -vgit branch --mergedgit branch --no-mergedgit push origin bug-123git push origin bug-123:new-branchgit checkout -b bug-123 origin/bug-123git push origin :bug-123Effectuer le rebase entre la branche bug-123 et master :
git checkout experiment
git rebase masterPlus d'informations et d'explications sur le Rebasing.
Pour basculer d'une branche à une autre, il est nécessaire de faire le commit des modifications actuelles avant de changer de branche. Si le changement est nécessaire sans effectuer le commit, il est possible de créer un stash. Le stash fonctionne comme une branche temporaire contenant uniquement les modifications non encore commit.
git stashgit stash listgit stash applygit stash apply stash@{2}Où 2 est l'index du stash souhaité.
git stash branch ma_branchegit commit --amend -m "Mon nouveau message"En modifiant les trois derniers commits:
git rebase -i HEAD~3L'éditeur s'ouvrira avec les lignes des trois derniers commits.
N'oublie de me dizer se quiseres mais traduções!
Suivez les mêmes étapes ci-dessus, mais marquez les commits à fusionner avec squash.
git filter-branch --tree-filter 'rm -f passwords.txt' HEADLe bisect (recherche binaire) est utile pour trouver un commit qui cause un bug ou une incohérence dans une série de commits.
git bisect startgit bisect badgit bisect good vs-1.1GIT va naviguer entre les commits pour aider à identifier le commit problématique. Si le commit actuel n'a pas de problème, marquez-le comme bon.
git bisect goodSi le commit a un problème, marquez-le comme mauvais.
git bisect badAprès avoir trouvé le commit problématique, pour revenir à HEAD utilisez :
git bisect resetN'hésitez pas à ajouter plus d'informations ou à faire des corrections. Forkez-moi !
- Modificado (modified);
- Preparado (staged/index)
- Consolidado (comitted);
git help
git help add
git help commit
git help <qualquer_comando_git>
As configurações do GIT são armazenadas no arquivo .gitconfig localizado dentro do diretório do usuário do Sistema Operacional (Ex.: Windows: C:\Users\Documents and Settings\Leonardo ou *nix /home/leonardo).
As configurações realizadas através dos comandos abaixo serão incluídas no arquivo citado acima.
git config --global user.name "Leonardo Comelli"
git config --global user.email [email protected]
git config --global core.editor vim
git config --global merge.tool vimdiff
git config --global core.excludesfile ~/.gitignore
git config --list
Os nomes de arquivos/diretórios ou extensões de arquivos listados no arquivo .gitignore não serão adicionados em um repositório. Existem dois arquivos .gitignore, são eles:
-
Geral: Normalmente armazenado no diretório do usuário do Sistema Operacional. O arquivo que possui a lista dos arquivos/diretórios a serem ignorados por todos os repositórios deverá ser declarado conforme citado acima. O arquivo não precisa ter o nome de .gitignore.
-
Por repositório: Deve ser armazenado no diretório do repositório e deve conter a lista dos arquivos/diretórios que devem ser ignorados apenas para o repositório específico.
git init
git status
git add meu_arquivo.txt
git add meu_diretorio
git add .
git add -f arquivo_no_gitignore.txt
git commit meu_arquivo.txt
git commit meu_arquivo.txt meu_outro_arquivo.txt
git commit meuarquivo.txt -m "minha mensagem de commit"
git rm meu_arquivo.txt
git rm -r diretorio
git log
git log -p -2
git log --stat
git log --pretty=oneline
git log --pretty=format:"%h - %an, %ar : %s"
- %h: Abreviação do hash;
- %an: Nome do autor;
- %ar: Data;
- %s: Comentário.
Verifique as demais opções de formatação no Git Book
git log -- <caminho_do_arquivo>
git log --summary -S<palavra> [<caminho_do_arquivo>]
git log --diff-filter=M -- <caminho_do_arquivo>
- O pode ser substituido por: Adicionado (A), Copiado (C), Apagado (D), Modificado (M), Renomeado (R), entre outros.
git log --author=usuario
git blame -L 12,22 meu_arquivo.txt
Este comando deve ser utilizando enquanto o arquivo não foi adicionado na staged area.
git checkout -- meu_arquivo.txt
Este comando deve ser utilizando quando o arquivo já foi adicionado na staged area.
git reset HEAD meu_arquivo.txt
Se o resultado abaixo for exibido, o comando reset não alterou o diretório de trabalho.
Unstaged changes after reset:
M meu_arquivo.txt
A alteração do diretório pode ser realizada através do comando abaixo:
git checkout meu_arquivo.txt
git remote
git remote -v
git remote add origin [email protected]:leocomelli/curso-git.git
git remote show origin
git remote rename origin curso-git
git remote rm curso-git
O primeiro push de um repositório deve conter o nome do repositório remoto e o branch.
git push -u origin master
Os demais pushes não precisam dessa informação
git push
git pull
git fetch
git clone [email protected]:leocomelli/curso-git.git
git tag vs-1.1
git tag -a vs-1.1 -m "Minha versão 1.1"
Para criar uma tag assinada é necessário uma chave privada (GNU Privacy Guard - GPG).
git tag -s vs-1.1 -m "Minha tag assinada 1.1"
git tag -a vs-1.2 9fceb02
git push origin vs-1.2
git push origin --tags
O master é o branch principal do GIT.
O HEAD é um ponteiro especial que indica qual é o branch atual. Por padrão, o HEAD aponta para o branch principal, o master.
git branch bug-123
git checkout bug-123
Neste caso, o ponteiro principal HEAD esta apontando para o branch chamado bug-123.
git checkout -b bug-456
git checkout master
git merge bug-123
Para realizar o merge, é necessário estar no branch que deverá receber as alterações. O merge pode automático ou manual. O merge automático será feito em arquivos textos que não sofreram alterações nas mesmas linhas, já o merge manual será feito em arquivos textos que sofreram alterações nas mesmas linhas.
A mensagem indicando um merge manual será:
Automerging meu_arquivo.txt
CONFLICT (content): Merge conflict in meu_arquivo.txt
Automatic merge failed; fix conflicts and then commit the result.
git branch -d bug-123
git branch
git branch -v
git branch --merged
git branch --no-merged
git push origin bug-123
git push origin bug-123:new-branch
git checkout -b bug-123 origin/bug-123
git push origin:bug-123
Fazendo o rebase entre um o branch bug-123 e o master.
git checkout experiment
git rebase master
Mais informações e explicações sobre o Rebasing
###Stash
Para alternar entre um branch e outro é necessário fazer o commit das alterações atuais para depois trocar para um outro branch. Se existir a necessidade de realizar a troca sem fazer o commit é possível criar um stash. O Stash como se fosse um branch temporário que contem apenas as alterações ainda não commitadas.
git stash
git stash list
git stash apply
git stash apply stash@{2}
Onde 2 é o indíce do stash desejado.
git stash branch meu_branch
git commit --amend -m "Minha nova mensagem"
Alterando os três últimos commits
git rebase -i HEAD~3
O editor de texto será aberto com as linhas representando os três últimos commits.
pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added catfile
Altere para edit os commits que deseja realizar alterações.
edit f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added catfile
Feche o editor de texto.
Digite o comando para alterar a mensagem do commit que foi marcado como edit.
git commit –amend -m “Nova mensagem”
Aplique a alteração
git rebase --continue
Atenção: É possível alterar a ordem dos commits ou remover um commit apenas mudando as linhas ou removendo.
Seguir os mesmos passos acima, porém marcar os commtis que devem ser juntados com *squash
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
O bisect (pesquisa binária) é útil para encontrar um commit que esta gerando um bug ou uma inconsistência entre uma sequência de commits.
git bisect start
git bisect bad
git bisect good vs-1.1
O GIT irá navegar entre os commits para ajudar a indentificar o commit que esta com o problema. Se o commit atual não estiver quebrado, então é necessário marca-lo como bom.
git bisect good
Se o commit estiver com o problema, então ele deverá ser marcado como ruim.
git bisect bad
Depois de encontrar o commit com problema, para retornar para o HEAD utilize:
git bisect reset
Sinta-se a vontade para realizar adicionar mais informações ou realizar correções. Fork me!
