Git permits developers to manage their projects and host them on a platform like GitHub and GitLab. In Git, all contributors to the particular project work in the branches and directories. While working in one repository, it is difficult for the developer to switch to another directory/branch without saving the changes. To handle such cases, Git allows the user to create multiple worktrees of different branches. So, that the user can switch between them easily, without losing the currently doing changes.
This tutorial will provide the steps-based procedure to work and manage multiple working directories using Git worktrees.
How to Work with Multiple Working Directories Using Git Worktree?
To work with multiple working directories using Git worktrees, walk through the below-provided instructions.
Step 1: Open Git Directory
Open Git bash and move to the Git repository using the βcdβ command:
Step 2: List Available Worktree
List down the available worktree using the provided command:
For now, thereβs only one worktree in which we are working.
Step 3: Add Multiple Worktrees
Add multiple wokrtrees in Git using the following syntax and specify the directory name and branch name:
Letβs say we want to add βmodule-1β in the βbetaβ branch, to do so, run the provided command:
Likewise, for adding the βmodule-2β in the βalphaβ branch, use the following command:
Step 4: Check Worktrees
Now, again list down the available worktrees using the following command:
The above image shows that the three worktrees are available.
Step 5: Switch Multiple Directories
To switch to the desired working directory, use the βcdβ command and specify the directory name. See the following command implementation:
The user has been switched to βmodule-1β under the beta branch.
Similarly, you can switch to the βmodule-2β which is in alpha branch as shown:
Work in Multiple Worktrees Directories
Letβs do some work in the βmodule-1β worktree. To do so, consider the following steps.
Step 1: Create a File
Create the file through the βtouchβ command:
Step 2: Track File
Track the created file using the provided βgit addβ command:
Step 3: Commit Changes
Commit the changes by running the mentioned command:
Step 4: Push Project
Lastly, push the project file via the βgit pushβ command:
Conclusion
Git allows users to create worktrees and manage multiple working directories and branches simultaneously. To create a worktree use the βgit worktree add <Directory Name> <Branch Name>β syntax, and specify the directory and branch name. After creating it, use the βcdβ command to switch between them. This guide has provided a detailed guide on Git worktrees with multiple working directories.