Comment changer de branche dans Git - Logilax (2024)

Comment changer de branche dans Git - Logilax (1)

Dans Git, vous pouvez changer la branche avec lepaiement gitcommande.

Pour passer à une branche existante :

git checkout 

Pour créer une nouvelle branche et y basculer :

git checkout -b 

Ce qui précède vous montre une méthode traditionnelle rapide pour changer de branche. Mais en 2019, une nouvelle solutioncommutateur gita été ajouté qui est beaucoup plus facile à mémoriser et pratique, en particulier pour les nouveaux utilisateurs de Git.

Il s'agit d'un guide complet sur la modification des branches dans Git.Vous apprendrez à utiliserpaiement gitetcommutateur gitcommandes avec des exemples illustratifs. Plus important encore, vous apprenez quelle est la différence entre les deux. Vous apprendrez également comment passer à une branche distante et comment passer à un commit particulier dans une autre branche.

1. Changer de branche avec la commande Git Checkout

Traditionnellement, la modification de la branche Git se produit avec lepaiement gitcommande. Si vous souhaitez passer à une branche existante, exécutez :

git checkout 

Et remplaceravec le nom de la succursale que vous souhaitez payer.

Si vous souhaitez créer une nouvelle branche et y effectuer un paiement en même temps, vous pouvez exécuter la commande suivante :

git checkout -b 

Où vous devez remplacer leavec le nom de la nouvelle succursale.

Exemple

Voyons un exemple concret avec un vrai projet Git.

Avant de passer à une branche existante, vous devez savoir quelles branches existent. Pour voir quelles branches il y a, exécutez lebranche gitcommande.

Par exemple, sur mon exemple de référentiel local, vous avez le choix entre plusieurs branches :

Comment changer de branche dans Git - Logilax (2)

Disons que nous voulons travailler avec la branche appelée "fonctionnalité“. Pour commencer à apporter des modifications, vous devez modifier (vérifier) ​​cette branche avec lepaiement gitcommande:

fonctionnalité de paiement git

Une fois que nous avons exécuté cette commande, assurons-nous que la branche que nous sommes est bien la "fonctionnalité" bifurquer. Pour ce faire, lançons lebranche gitcommande à nouveau car elle montre non seulement les branches, mais celle que nous avons actuellement enregistrée.

Comment changer de branche dans Git - Logilax (3)

Cool! Cela vous montre comment passer à une branche existante dans Git.

Passons ensuite à une nouvelle branchema-nouvelle-succursalequi n'existe pas. Pour ce faire, utilisons legit checkout -b commande:

git checkout -b ma-nouvelle-branche

Après avoir exécuté cette commande, faisonsbranche gitpour voir que le changement a bien eu lieu :

Comment changer de branche dans Git - Logilax (4)

Comme vous pouvez le voir sur la capture d'écran ci-dessus, nous sommes maintenant passés à une branche nouvellement créée appeléema-nouvelle-succursale.

Si vous n'avez pas utilisé le-boption danspaiement gitlors du passage à une nouvelle branche, vous verriez une erreur comme celle-ci :

erreur : pathspec 'my-new-branch' ne correspond à aucun fichier connu de git

Cela signifie que vous essayez de passer à une branche inexistante. Le-best là pour créer la nouvelle branche pour vous afin que vous puissiez y accéder.

C'est ça! Vous avez maintenant appris à modifier les branches en branches existantes ainsi qu'en nouvelles branches.

2. Changer de branche avec 'git switch'

En 2019, une nouvelle façon de changer de branche dans Git a été introduite en ajoutant un nouveaucommutateur gitcommande.

L'idée decommutateur gitest très semblable àpaiement git. Vous pouvez utiliser lecommutateur gitcommande pour passer à une nouvelle branche ou à une branche existante.

Pour passer à une branche existante, vous pouvez utilisercommutateur gitavec la syntaxe suivante :

git switch 

Et pour passer à une nouvelle branche, exécutez :

git switch -c 

Très semblable àpaiement git, droite?

Plus loin dans ce guide, vous apprendrez quelle est la différence entrecommutateur gitetpaiement gitcommandes pour vous aider à choisir entre les deux.

Exemple

Voyons un exemple concret d'utilisation decommutateur gitcommande.

Avant de changer de branche, vous devez savoir quelles branches sont disponibles. Comme vous l'avez déjà appris, vous pouvez le faire avec lebranche gitcommande.

Comment changer de branche dans Git - Logilax (5)

Passons maintenant au "fonctionnalité” branche en utilisantcommutateur git:

fonctionnalité de commutateur git

Vérifions que le changement a bien eu lieu en exécutantbranche gitencore:

Comment changer de branche dans Git - Logilax (6)

Bien!

Comme autre exemple, passons à une nouvelle branche appeléema-nouvelle-succursale. Cette fois, vous avez besoin decommutateur git -cpossibilité de créer une nouvelle branche :

git switch -c ma-nouvelle-branche

Exécutons lebranche gitcommande une fois de plus pour voir que la nouvelle branche a été créée et que nous y sommes en ce moment :

Comment changer de branche dans Git - Logilax (7)

'git checkout' vs 'git switch'

Dans les exemples précédents, vous avez appris à utiliserpaiement gitetcommutateur gitchanger de branche.

Mais comme vous l'avez peut-être remarqué,ces deux commandes semblent faire exactement la même chose. Cela vous fait probablement vous demander quelle est la différence entre ces deux commandes et laquelle devez-vous utiliser.

Lorsqu'il s'agit de changer de branche ou de créer une nouvelle branche et d'y changer,paiement gitetcommutateur gitfonctionnent en effet de la même manière.

La principale raison pour laquelle lecommutateur gita été introduit était de clarifier la confusion causée par lepaiement gitcommande.

Avecpaiement git, vous pouvez faire deux choses principales :

  1. Changer de branche (git checkout -b ougit checkout )
  2. Réinitialiser ou annuler les modificationsaux fichiers (git checkout )

Il existe donc deux opérations entièrement différentes que vous pouvez effectuer avec la même commande.Ce qui aurait plus de sens, c'est d'ajouter de nouvelles commandes pour ces opérations au lieu d'avoir une seule commande pour les deux. C'est exactement ce que Git a fait en 2019. Ils ont ajouté deux commandes :

  1. commutateur gitpour changer de branche.
  2. restauration gitpour annuler les modifications.

Notez qu'au moment de la rédaction, les deux commandes sont expérimentales. Cela signifie qu'il pourrait y avoir des changements de comportement à l'avenir.

Comment changer de branche dans Git - Logilax (8)

A choisir entrepaiement gitetcommutateur git, considérez ces choses:

  1. commutateur gitest encore expérimental. Toute future modification potentielle de cette commande pourrait affecter votre flux de travail.
  2. commutateur gitest une commande distincte pour changer de branche. Cette commande est plus facile à comprendre et à mémoriser quepaiement git.

Pour ramener à la maison : Utilisez lecommutateur gitcommande pour changer de branche. C'est ce que la commande est censée faire !

3. Comment passer localement à une succursale distante

Parfois, vous devrez peut-être passer à une branche Git distante à partir de votre référentiel local.

Pour basculer vers une branche distante, vous devez récupérer la branche distante dans votre dépôt local à l'aide de la commande git fetch. Ensuite, vous pouvez payer à la succursale avec legit paiement -tcommande. (Le-test l'abréviation de-pistece qui signifie que cette action commence également à suivre la branche distante).

git fetchgit checkout -t /

Exemple

Voici un exemple de dépôt de projet avec deux branchesprincipaletnouveaux changements de code.

Comment changer de branche dans Git - Logilax (9)

Localement, il n'y a queprincipalbifurquer.

Maintenant, vérifions lenouveaux changements de codebranche qui n'existe que sur le référentiel distant :

git fetchgit checkout -t origine/nouveaux-changements de code

Voici à quoi ressemble l'exécution de ces commandes :

Comment changer de branche dans Git - Logilax (10)

Legit chercherLa commande indique qu'il existe une nouvelle branche sur l'origine distante. Lepaiement gitcommande passe alors à cette branche et commence à la suivre.

4. Comment changer de branche en un commit spécifique

Dans Git, vous pouvez utiliser lepaiement gitcommande pour changer de branche et atterrir sur un commit particulier.

Voici à quoi ressemble la syntaxe :

git checkout -B  

Cela change la branche en une branche appeléeNom de la filialeet vérifie un commit identifié parcommit-hachage.

Exemple

Disons que vous êtes dans unfonctionnalitébranche et vous souhaitez revenir à laprincipalbranche vers un commit spécifique.

La première chose que vous devez faire est de vérifier la liste des commits disponibles dans leprincipalbifurquer:

$ git log main --oneline --graph* 84a14b9 Version 1.10 commit (master, HEAD)* 5da7j6f Add file2* 1h7e678 Add file1* ccb963f Initial commit

Passons au second commit (celui avant leDIRIGERcommettre):

$ git checkout -B main 5da7j6fBasculement et réinitialisation de la branche 'main'

Résumé

Aujourd'hui, vous avez appris à changer de branche dans Git.

La façon traditionnelle de changer de branche consiste à utiliser lepaiement gitcommande.

git checkout git checkout -b 

Mais de nos jours, une commande plus pratiquecommutateur gitexiste.

git switch git switch -c 

Merci d'avoir lu. Bon codage !

Lire aussi

  • Comment annuler un commit dans Git
  • Comment voir les différences entre deux branches Git
Comment changer de branche dans Git - Logilax (2024)

FAQs

How to change branch using git command? ›

New Branches

The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.

How do I switch to a remote branch? ›

Switching to a remote branch​

To checkout a remote branch, you will need to fetch the contents of the branch using git fetch –all first. Then use the same command git checkout RemoteBranchName to switch to remote branch. You might have noticed that it is the same command used to switch to a local branch.

How to rename local git branch? ›

To do this, use the following steps:
  1. Switch to the master via the command “git checkout master”.
  2. Now enter the following command if you want to rename a Git branch: “git branch -m old-name new-name”.
  3. To ensure that the rename was successful, retrieve the current status of the branch using the “git branch -a” command.
Apr 28, 2023

How to switch from master to feature branch in git? ›

First, make sure that the target branch exists by running the “git branch” command. Now that you made sure that your branch exists, you can switch from the master branch to the “feature” branch by executing the “git checkout” command. That's it!

How to change branch without commit? ›

If you have made changes to the current branch and want to switch to a different branch, but do not want to commit or stash your changes, you can use the git checkout command with the -f option to force the switch. This will discard any uncommitted changes and switch to the specified branch.

How do I list remote branches? ›

How to List Remote Branches in Git?
  1. git branch -r . Lists all the remote branches.
  2. git branch -r -v . Lists all the remote branches with the latest commit hash and commit message.
  3. git ls-remote . Lists all the references in the remote repository, including the branches.
  4. git remote show [remote_name ]. ...
  5. git branch -a .
Apr 5, 2023

How do I pull another branch from a remote? ›

You can do this with the git fetch command. The git fetch command goes out to your remote project and pulls down all the data from that remote project that you don't have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time.

Can we change branch name? ›

You can change the name of a branch in a repository. People with write permissions to a repository can rename a branch in the repository unless it is the default branch or a protected branch. People with admin permissions can rename the default branch and protected branches.

How to replace local git branch with remote? ›

That's as easy as three steps:
  1. Delete your local branch: git branch -d local_branch.
  2. Fetch the latest remote branch: git fetch origin remote_branch.
  3. Rebuild the local branch based on the remote one: git checkout -b local_branch origin/remote_branch.
Feb 9, 2012

How do I change my branch name locally and remotely? ›

  1. Rename your local branch: If you are on the branch you want to rename: git branch -m new-name. ...
  2. Delete the old-name remote branch and push the new-name local branch: git push origin :old-name new-name.
  3. Reset the upstream branch for the new-name local branch: Switch to the branch and then: git push origin -u new-name.
Jun 2, 2015

How do I switch from one branch to master? ›

At any time in the course of your work you can easily view branches by running the git branch command:
  1. git branch.
  2. * master.
  3. git checkout master.
  4. Switched to branch 'master'
Oct 1, 2021

How do I change my branch from main to master? ›

Changing the default branch
  1. On GitHub.com, navigate to the main page of the repository.
  2. Under your repository name, click Settings. ...
  3. Under "Default branch", to the right of the default branch name, click .
  4. Select the branch dropdown menu and click a branch name.
  5. Click Update.

How do I pull changes from branch to master? ›

Steps to merging branch into master
  1. git fetch.
  2. git rebase origin/master.
  3. git checkout master.
  4. git pull origin master.
  5. git merge test.
  6. git push origin master.

How do I checkout and create a new branch? ›

The easiest way to create a Git branch is to use the “git checkout” command with the “-b” option for a new branch. Next, you just have to specify the name for the branch you want to create. To achieve that, you will run the “git checkout” command with the “-b” option and add “feature” as the branch name.

How to change branch type to feature in git? ›

Changing branch type
  1. Choose Tools > Administration > Branch Maintenance. ...
  2. Select a workspace branch and click Change Type. ...
  3. Select a Branch Type to change the workspace branch to a baseline branch.
  4. Select a New Owner to change the workspace branch owner.
  5. Enter the New Branch Name.

Top Articles
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 5367

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.