Sometimes users work on multiple projects in Git simultaneously and they need to frequently switch between branches. Before switching from one branch to another they are required to save changes each time. However, they want to switch branches without saving changes in the repository. To do so, the âgit checkoutâ command can be used along with the â-fâ or â–fâ options.
This post will demonstrate the method for forcing Git checkout.
How to Force Git Checkout?
To force Git checkout, follow the below stated steps:
- Navigate to the Git root repository.
- Check all previous data by running the âlsâ command.
- Execute the âstartâ command to start a file.
- Move the modified file to the Git tracking area.
- Use the âgit statusâ command to view the current state of the Git working repository.
- Use â-fâ or â–fâ along with the âgit checkoutâ command for switching branches.
Step 1: Move to Git Root Directory
First, run the âcdâ command and navigate to the Git root directory:
Step 2: List All Content
List all the available content of the Git root directory with the help of the âlsâ command:
It can be observed that the content has been listed successfully:
Step 3: Update the File
Execute the âstartâ command along with the file name and open it for modifications:
After executing the above command, enter the desired data in the file and save it:
Step 4: Add File
To save a modified file in the Git repository, run the âgit addâ command:
Step 5: Check Status
Utilize the âgit statusâ command for viewing the current status of the working directory:
The below-provided output stated that the âmyfile.txtâ has been modified successfully and placed in the working area:
Step 6: List all Branches
Execute âgit branchâ to list Git local branches:
According to the below-given output, the âmasterâ is the current working branch, and want to switch to the âfeatureâ branch:
Step 7: Force Git Checkout
To check out forcefully from one branch to another, run the âgit checkoutâ command along with the â-fâ or â–forceâ option and branch name:
As you can see, we have successfully switched from the âmasterâ branch to the âfeatureâ branch:
Thatâs all! You have learned the method for forceful checkout in Git.
Conclusion
To force Git checkout, first, navigate to the Git root repository and check all available data by executing the âlsâ command. Furthermore, modify the file and insert an updated file into the repository with the help of the âgit addâ command. Then, check the current status of the repository and use the âgit checkoutâ command with the â-fâ or â-forceâ option for switching between branches. This blog described the procedure for forcing the Git checkout.