If you have any doubt/question then please feel free to raise the issue on github or can contact me on my other social media profiles and link of those social media profiles can be found on my github profile page. And also if there's any correction or new addition from your side for my cheatsheet then I would be priviliged to get your contritbution. 🙏🏻 Hope you have a good time here 🥰
All the following steps are prefered to be followed and executed on 'Git Bash' after installing it on your machine.
To check your git version
git --version- Three cases:
If your Git version is 2.14.1 or earlier:
Uninstall Git, download the latest Git, and install it again.
And versions between 2.14.2 and 2.16.1:
Use command
git updateIf the version is equal to or greater than Git 2.16.1(2):
Use command
git update-git-for-windowsgit config --global user.name yournamegit config --global user.email "yourmail@gmail.com"To know it is set up or not :
git config --global user.name(your username as output)
git config --global user.email(your email as output)
(This step is optional is you already have an existing .gitignore file)
"touch" creates a new blank file of .gitignore
touch .gitignoreedit the .gitignore file and add the name of the folder which we dont want to upload
FYI : If we want to have a repository then 2 options we have,
1. git init (it initializes from the start)
OR
2. clone (it clones a repo we want and clones it's whole data from server)
Will create a .git file, keep hidden files enable to see it
git initVery imp Flow of git -
Untracked file(On local device)----> Staged(filewhich we wish to put on git) <---|
| |
| { Commit } |
v |
Unmodified file on git |
(Goes on git which we can edit/remove)[snapshot taken by git] |
| |
| (If edited) |
v |
Modified file on git >------(Back to staging)------|
To put all the contents at staging area and . means staging all new and modified items excluding deleted ones.
git add .If dont want to put all files then use the following syntax
git add filenameIf want to put all the files of the directory at staging then,
git add -AIf want to put only the modified and deleted items at staging then,
git add -uTo stage a New_folder(*Remember, don't keep a space in the folder name and keep as eg. New_folder) :
git add New_folder/To stage say a specific.txt file in a nested folder :
git add folder1/folder2/folder3/specific.txt👉🏻 Can check status ✔ now by
git status-
git commitmeans taking a snapshot -
So
git addandgit commitmakes a snapshot associated to the changes we made -
But right now nothing is added to my repo so using message for commit as "Initial commit"
If this command is executed then an editor will open then press i to edit and write the message Initial commit and then press Esc key and then type :wq to save and exit the file.
git commit- ALTERNATE EASY METHOD
git commit -m "Initial commit"- I prefer the following commands as it skips staging and directly commits :
-aCommits modified and deleted files- Remember this following will mostly work when we have done tracking(staging) with the
git addcommand atleast once for tha repository.
git commit -a -m "msg"Or
git commit -am "msg"- If want to commit one one files separately with seaparate messages then,
git add file1.txtgit commit -m "Commiting file1.txt with custom message"Similarly,
git add file2.txtgit commit -m "Commiting file2.txt with custom message"- To know if commit is done, check the log which will give information about about all commits.
git log --onelineTo finally push the "master" branch on "origin" url
git push -u origin master- If once
push -u originis used then next time we just writegit pushwhich will by default push it the branch which was last commanded with-u - Technically, the
-uflag adds a tracking reference to the upstream server you are pushing to.
What is important here is that this lets you do a git pull without supplying any more arguments.
For example, once you do a git push -u origin master, you can later call git pull and git will know that you actually meant git pull origin master.
Otherwise, you'd have to type in the whole command.
Make a repo on github with no files(no readme, etc) just as an example 😉
TO CONNECT TO GITHUB'S REMOTE REPOSITORY WITH OUR LOCAL REPOSITORY(Folder on the PC which we need to upload on github)
git remote add origin git@github.com:meetmakwana19/about-git.gitgit@github.com:meetmakwana19/about-git.git is the SSH link of the github repository on which we want to connect and upload our local repository.
MEANING A REMOTE NAMED origin IS ADDED AND OUR URL CAN BE CALLED AS origin
- TO SEE REMOTE
git remoteOutput:
origin- TO SEE URL
git remote -vOutput :
origin git@github.com:meetmakwana19/about-git.git (fetch)
origin git@github.com:meetmakwana19/about-git.git (push)⚠⚠ NOW GITHUB IS NOT LINKED WITH OUR PC SO TO PUSH THE LOCAL REPO TO GITHUB DO THE FOLLOWING :
-
Go to this Github documentation by clicking here to generate new ssh key.
-
Paste the text below, substituting in your GitHub email address.
ssh-keygen -t ed25519 -C "your_email@example.com" -
To generate Agent pid (Execute this command in git bash if using Windows)
eval "$(ssh-agent -s)"
- Add private key to the ssh agent, change directory to the
.sshfolder and try to run the folder command.
ssh-add ~/.ssh/id_ed25519 - Add private key to the ssh agent, change directory to the
If things are not working out check this
-
To read the ssh key I went to the directory given by previous eval command and opened .pub file with notepad
-
Copied the ssh key and added it as a new ssh key on Github's Acc settings > SSH Keys > New SSH Key(green button).
-
Went to repo's "Code" tab and clicked on "Code 🔽" green button and copied ssh url.
-
Copied the SSH url which looks like
git@github.com:meetmakwana19/about-git.git
- Do all the setps as above by starting with generating ssh keys for another email id like the following :
ssh-keygen -t ed25519 -C "other_email@example.com"- Type the name of new file for saving key with complete path like :
C:\Users\meet.makwana/.ssh/id_ed25519_other - Copy paste the public key in your another github account's settings.
- Type the name of new file for saving key with complete path like :
eval "$(ssh-agent -s)"- Add that other private key to the ssh-agent :
ssh-add ~/.ssh/id_ed25519_other - Now your
.ssh/folder has 2 private 2 public keys for 2 different github accounts. - Make a
configfile without any file extensions in your.ssh/folder and write the following into it :
# Default account (main account)
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
# Other account
Host github-other.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_other
- Now change the email id in your required directory for that other github word like
git config user.email "other_email@gmail.com" - Now clone or push the repo related to that other account using that defined host like
git clone git@github-other.com:meetmakwana19/about-git.gitor
git remote set-url origin git@github-other.com:meetmakwana19/about-git.git- Have to set the Github's SSH url to the local machine
git remote set-url origin git@github.com:meetmakwana19/about-git.git- To finally push the "master" branch on "origin" url
git push -u origin master(If once push -u origin is used then next time we just write git push which will by default push it the branch which was last commanded with -u)
- To push to another branches on GitHub ,
-
git checkout newBranch
-
git push -u origin
git commit -a -m "Skipped staging area and commited directly"-a is selecting All for stagging and -m is for Message.
From local storage & staging area
git rm `filename`From staging area only, local one will remain the same
git rm --cached `filename`- Delete file/folder from remote repository :
1] First deleting from local & staging area.
git rm --cached `filename`For a folder (*Remember, don't keep a space in the folder name and keep as eg. New_folder),
git rm --cached -r New_folder/2] Then just commit nd push the changes.
git commit -m "Removed"git push- Delete multiple files in one go 😎
1] From both local and remote repository
git rm file1.png file2.txt file3.pyOr
1] From only remote repository while keeping the local one untouched.
git rm --cached file1.png file2.txt file3.py2] Then just commit nd push the changes.
git commit -m "Removed"git push$ git status -s
MM about.html(this will be in green meaning modified in staging area)(2nd M will be in red meaning modified in working tree)
M site.html (this will be in red meaning modified in working tree )
?? waste.html-
Making a new folder on PC and opening git bash(by right click menu) over there to clone into that folder.
-
Will go to any public repository on Github and under code tab will copy the
httpslink. -
In the new folder's git bash we'll write
git clone https://github.com/meetmakwana19/To-Do-List.git meet
where
https....is the link of repo to be cloned andmeetis the folder name where the repo to be cloned inside our opened folder.git clone https://github.com/meetmakwana19/To-Do-List.git
*If "meet" folder name not given then a folder of remote repository's name will be created.
-
Clone to a specific_branch
git clone -b specific_branch remote_link_SSH_or_HTTPS
-
A branch is used to make a different workspace on the repository to dump/upload on that different branch to work separately without causing any trouble to the anothe branches.
-
An analogy of a Tree is perfectt example to understand as different branches are separated on the same Tree where Tree is considered to be the repository.
-
BY DEFAULT, BRANCH IS "MASTER".
TO CREATE A BRANCH
git branch `name_of_branch`TO KNOW THE NAMES OF ALL BRANCHES:
git branchSHORTHAND FOR CREATING AND ENTERING(SWITCHING TO IT) THE BRANCH AT THE SAME TIME
git checkout -b newBranchTO SWITCH TO ANOTHER BRANCH
Meet@LAPTOP ~/OneDrive/Desktop/New folder (master)
$ git checkout feature1Switched to branch 'feature1'
Meet@LAPTOP ~/OneDrive/Desktop/New folder (feature1)
$ git status
On branch feature1
nothing to commit, working tree clean**Keep the file open and see the changes when switching between branches.
- To push to a specific branch to a remote names
origin
git push origin branch_name- To merge a specific branch with another branch say
masterbranch then switch (checkout) to it and do the following
git merge specific_branch- Delete a specific branch from the local repository
git branch -d specific_branch- Delete a specific branch from the remote
origin
git push origin --delete specific_branch- To rename any_branch
git branch -m new_nameThen after all these or any of these push changes forcibly,
git push -f origin myBranchTO GET LOG OF ALL OUR COMMITS
git logTO FILTER OUT LOGS OF COMMITS.
FOR EG. TO GET LAST 2 COMMITS (it also shows the changes)
git log -p -2(press q to exit from the log viewer)
WILL COMPARE AND SHOW THE DIFFERENCES BETWEEN THE CURRENT FILES(WORKING TREE) AND STAGED FILES
git diffWILL COMPARE AND SHOW THE DIFFERENCES BETWEEN THE LAST COMMIT AND STAGED FILES
git diff --staged.gitignore file has the list of all the files and folders which we dont want to track with git.
SHOULD BE KNOWN :
-
TO IGNORE ALL THE FILE-TYPES(.log), ADD THIS IS IN .gitignore eg: (.log)
*.log -
TO IGNORE A FOLDER USE A FORWAD SLASH
`folder_name`/
To restore files from last commit. Used to get back the last version of the file if someone has wrongly edited and saved it. Essentially matching with the last commit !!
git checkout `filename`To match all the files with last commit and change and them according to the last commit !!
git checkout -fCan make a new folder and run git init by opening git bash in that folder.
git clone https_link- Whereas
git pullon the other hand is not same as clone command. - So git pull means you are fetching the last modified changes from the remote repository and kinda refreshing your local repository to get the changes.
- It will be often used while a team is collaborating on a repo.
- It is basically
git fetch+git merge.
git pull https_linkSo,
Clone: Get a working copy of the remote repository.
Pull: I am working on this, please get me the new changes that may be updated by others.
git clone <remote-url>
- create a new directory
git init// init new repositorygit remote add origin <remote-url>// add remotegit fetch// fetch all remote branchsgit switch <default_branch>// switch to the default branch
git pull
- fetch ALL remote branches
- merge CURRENT local branch with tracking remote branch (not another branch) (if local branch existed)
git pull <remote> <branch>
- fetch the remote branch
- merge CURRENT local branch with the remote branch (if local branch existed)
git restore --staged staged_file_name_or_pathgit reset staged_file_name_or_pathgit reset HEAD staged_file_name_or_pathHEAD points to location at which our repository is at current state at current time & space.
- To remove all staged files from staging area
git restore --staged
or
git restore --staged .git resetgit reset HEAD
or
git reset HEAD .
or
git reset HEAD --git reset HEAD~1Instead of 1, there could be any number of commits you want to unstage.
It's basically Ctrl+Z
IMP : But it's different because the file is not yet commited/staged.
git revert file.txtOr
git checkout -- file.txtrevert HEAD reverts the current state(HEAD) to the last commit.
git revert HEAD12abc34 is the 7 digit example git commit ID.
To know the git commit IDs of all the commits made.
git log --onelineThen use that ID for revert command.
git revert 12abc34After this command your terminal's text editor(Most likely Vim for git bash) will open and don't do anything if you dont want to write a custom commit message.
Just do :wq to save and exit the text editor which will make the revert work.
If you want to write your custom git message then press i and start editing the first line on the editor and then exit the edit mode by pressing Esc key and then :wq.
- Another way,
To know the git commit IDs(40 characters long) of all the commits made.
[Press q to exit the editor viewer after git log command.]
git logThen use that 40 characters long ID for revert command.
git revert 4e28d49dc37b66v755b6f95dc70c8e579z3830f8The above ID is example and please dont try to copy paste the same ID
Then,
git pushSay there are 5 commits, 1 being oldest(first) and 5 being latest.
Now you want to go to 2nd commit and delete all 3rd,4th,5th commits.
I mentioned DELETE i.e remove it's history totally and not like git revert command.
git reset is very powerfull to destroy those commits.
2 types :-
--hard will remove the commits history and undo changes of the commits at both local and remote levels.
40 digits commit ID mentioned in the command is where we want to shift our HEAD(Pointer) to and delete every commit above it.
git reset --hard 4e28d49dc37b66v755b6f95dc70c8e579z3830f8The above ID is example and please dont try to copy paste the same ID.
Then use -f flag which means push forcibly.
git push -f origin myBranchNeed to force push like this because we came back in the commits history on local level using git reset
But the remote is ahead of local in commits as the changes aren't yet pushed.
Thereforce, will need to force the push using -f.
--soft will destroy commits at remote level as well as local level
BUT won't undo/revert the changes of the destroyed commits at local repository. Therefore, called as soft reset.
git reset --soft HEAD~x~ = Tilde sign
x = number how much back in commit history you want to go.
Example : HEAD~3 means go back three commmits from the HEAD.
Then, we'll offcourse have to push the changes which will delete the commits even from the remote and won't display them.
- 2 ways to push forcibly,
git pushorgit push -u originwont work as we want to force push🌝
git push origin +masterOr
git push origin +master --force⚠ However, a huge downside of these reset commands(both hard and soft) is that it just makes the commmit invisible from our github repository
But when we have the exact link to the destroyed commit then we can access it's full files like try this
⚠Also, if there is only one commit in the repository then that cannot be deleted by these commands as these command take the Head to the mentioned commit by deleting the ones above it and not destroy the mentioned commit.
I wanted to unstage all the staged files so used the command git reset HEAD
But unknowingly I deleted dozens of important files from my local repository.
So the followings steps to take in such situation to restore the file of the local repository.
- Git keeps a log of all ref updates (e.g., checkout, reset, commit, merge). You can view it by typing:
git reflogSomewhere in this list is the commit that you lost.
Let's say you just typed git reset HEAD and want to undo it. My reflog looks like this:
The first line says that HEAD 0 positions ago (in other words, the current position) is 8efd6f0. It was obtained by resetting to HEAD~. The second line says that HEAD 1 position ago (in other words, the state before the reset) is f7e9df2. It was obtained by checking out a particular commit (though that's not important right now).
So, to undo the reset and go to a specific commit (85bfa92- where I want to go back, from where I lost the data)
git reset 'HEAD@{4}'or
git reset 85bfa92This will give lost of all files which were lost.
To obtain then back, we'll use the command checkout
git checkout 22_Class_Based_Components.md 22_news_app/.gitignore 22_news_app/README.md 22_news_app/SampleResponse.json 22_news_app/package-lock.json 22_news_app/package.json 22_news_app/public/favicon.ico 22_news_app/public/index.html 22_news_app/public/logo192.png 22_news_app/public/logo512.png 22_news_app/public/manifest.json 22_news_app/public/robots.txt 22_news_app/src/App.css 22_news_app/src/App.test.js 22_news_app/src/components/loading.gif 22_news_app/src/index.css 22_news_app/src/index.js 22_news_app/src/logo.svg 22_news_app/src/reportWebVitals.js 22_news_app/src/setupTests.js 23_Components_structuring.md 24_News_API.md 25_rcc_States.md 26_Looping_array.md 27_Fetching_from_API.md 28_Next_Previous_pages.md 29_Loading_Spinner&variable_pageSize.md 30_Categories&propTypes.mdWriting the names of all files together to restore them in one go.
git commit --amendAfter this command your terminal's text editor(Most likely Vim for git bash) will open.
To write your message press i and start editing the first line on the editor and then exit the edit mode by pressing Esc key and then :wq.
If you want to change the dates of multiple commits, you can do so by using an interactive rebase.
- Start an Interactive Rebase
- Decide how many commits back you want to change. For example, if you want to modify the last 3 commits:
- This will open your default text editor with a list of the last 3 commits.
git rebase -i HEAD~3-
Edit the Commits
- In the editor, you'll see something like this:
- The commits will be arranges in a fashion of newest to be at the bottom.
pick commit_hash Commit_message_3 pick commit_hash Commit_message_2 pick commit_hash Commit_message_1
- Enter
ikey to enter the insert mode. - Change
picktoeditfor each commit whose date you want to modify:
pick commit_hash Commit_message_3 edit commit_hash Commit_message_2 edit commit_hash Commit_message_1
- Save and close the editor by pressing
esckey and the typing:wqand pressEntern.
-
Amend Each Commit
- Git will stop at each commit, allowing you to amend it like :
Stopped at ef121d1... L25: Added explicit address typecasting theory You can amend the commit now, with git commit --amend Once you are satisfied with your changes, run git rebase --continue
- For each commit, run:
git commit --amend --date="YYYY-MM-DDTHH:MM:SS"- This will also open the editor. Save and exit it.
- Continue the Rebase. This will move on to the next commit in the rebase sequence.
git rebase --continue
- Edit the Next Commit (If Needed).
-
Rebase and update the branch after completing all the edit :
git rebase --continue- Now just push the changes. If you previously pushed these commits to a remote repository, you'll need to force push to update the remote branch with your new commit history:
git push --force-with-leaseIf you want to
- reset your branch to a specific commit,
- discard all commits above it,
- amend that commit with new changes,
- and push it back to the remote branch.
Here’s how to do it:
- Reset your branch to the target commit and get all the changes after that commit to the staging level
git reset --soft <commit-hash>--soft keeps all changes staged.
- Get those staged changes out of staging and make the necessary changes you wished to get in that commit
- Stage back all the changes
- Amend the commit
git commit --amendThis will update the commit message and include new changes.
- Force push the updated commit,
Since this rewrites history, you need to force push:
git push --force-with-lease<span style="color:yellow">some *yellow* text</span>- Used when we want to save current working directory/branch's work which can be incomplete and proceed to some other branch's work
- Useful while switching branches
- Useful when dont wanna commit incomplete progress of current branch.
- Normally we commit and then switch branches
- But if switching without doing a commit then 2 of the following things can either happn
- Switch to other branch carrying changes to other changes
- Git wont allow to switch and will ask to commit/stash the changes
- The command allows switching branches without commiting to the current branch
Stashmeaning is "to store something safely ata hidden place".- So git temporarily saves the data without committing
- Simple easiest way to stash current work in the current branch is
git stash
- Giving name to the stash
git stash save cool_name
- Stash all the changes including new untracked files
git stash -u
- Listing the available stashes
git stash list
- To get a specific stash back
git stash apply `index`
- To get back the stashed changes
git stash pop
- To stash only staged (indexed) files
git stash push --staged
- To stash only unstaged changes (keep staged)
git stash push --keep-index
git commit --date='year-month-day hour:minutes:seconds' -m "message"So it would look something like this:
git commit --date='2026-02-01 12:12:00' -m "message"- Tags are ref's that point to specific points in Git history.
- Tagging is generally used to capture a point in history that is used for a marked version release (i.e. v1.0.1).
- A tag is like a branch that doesn’t change.
- Unlike branches, tags, after being created, have no further history of commits.
- Git supports two types of tags:
lightweightandannotated.- A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit.
- Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).
- It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too.
- Listing the existing tags in Git is straightforward. Just type
git tag(with optional-lor--list):
git tag- This command lists the tags in alphabetical order; the order in which they are displayed has no real importance.
- You can also search for tags that match a particular pattern.
git tag -l "v1.8.5*"Annotated Tags
git tag -a v1.4 -m "my version 1.4"- You can see the tag data along with the commit that was tagged by using the
git showcommand:
git show v1.4Lightweight Tags
- To create a lightweight tag, don’t supply any of the
-a,-s, or-moptions, just provide a tag name:
git tag v1.4-lw- You can also tag commits after you’ve moved past them.
git tag -a v1.2 9fceb02 - m "my version v1.2"- By default, the git push command doesn’t transfer tags to remote servers
- This process is just like sharing remote branches — you can run
git push origin <tagname>.
git push origin v1.5- OR you can also use the
--tagsoption to transfer all the tags.
git push origin --tagsgit push --tags- On local level
git tag -d v1.4-lw- On remote level
git push origin --delete v1.4
- To rebase your branch on the latest main and maintain a linear history, run:
git fetch origin
git rebase origin/main
- If there are conflicts, Git will prompt you to resolve them. After resolving, continue rebase with:
git rebase --continue- Once the rebase is done, push the updated history. Again, this requires a force push since you rewrote the commit history.
git push origin <your-branch> --force- Say you have a series of linear commits like the following
62a1b7d (HEAD -> updates, origin/updates) chore: fixed messed up serial numbers
0071e39 Merge remote-tracking branch 'origin/master' into updates
2c3957a feat: added rebasing info
2675d8d (origin/master, origin/HEAD) Merge pull request #2 from meetmakwana19/updates- And you wish to get all the changes done in the top 3 commits back to stag level so you reset your branch to the commit below it i.e.
2675d8d.
git reset 2675d8d- Now your git history will look like :
2675d8d (origin/master, origin/HEAD) Merge pull request #2 from meetmakwana19/updates
.
.- Now your committed changes will be brought back to the staging level from where you can bring it out of stag and edit and restage and commit back.
- Find the Commit ID
git log --oneline- Start an interactive rebase from BEFORE the commit
You must rebase starting from the parent of the commit you want to edit:
git rebase -i ghi789^( ghi789^ means "the parent of ghi789" )
- Modify the Commit, A text editor will open showing a list of commits:
edit ghi789 Commit message 3 <-- Change "pick" to "edit"
pick jkl012 Commit message 4
pick mno345 Commit message 5Press i to enter in insert mode of the editor. Change pick to edit by typing for the commit you want to modify.
Save and exit by pressing Esc key and the typing :wq and Enter.
-
Make Changes & Amend the Commit
-
Now Git will stop at that commit.
-
Modify your files (if needed)
-
Stage the changes
-
Now you can amend the changes with a new commit message or the old one itself
-
For new message :
git commit --amend -m "Updated commit message or changes" -
For old message :
git commit --amend --no-edit
or simply
git commit --amend
-
-
Continue the rebase:
git rebase --continue
-
-
Since this rewrites history, force push
git push --forceor if you want a safer force push (only overwriting if you’re up-to-date), use:
git push --force-with-lease- Even if you already pushed, you can still amend the last commit and force push. (no matter local or remote HEAD commit you wish to change)
Steps :
- Make your changes to the file(s) locally.
- Stage the changes
- Amend the last commit:
git commit --amendIt will open your commit message editor.
You can keep the same message or edit it if you want.
Save and close the editor.
- Since this rewrites history, force push
git push --forceor if you want a safer force push (only overwriting if you’re up-to-date), use:
git push --force-with-leaseError can look something like this :
error: object file .git/objects/5c/e7c038a18323acee48ad13 is empty
fatal: loose object 5ce7c038a213 (stored in .git/objects/5c/e7c038a183d883) is corrupt
Solution learned from https://stackoverflow.com/a/31110176/17796286
Solution :
find .git/objects/ -type f -empty | xargs rm
git fetch -p
git fsck --full
- Finding empty .git object files and then
xargs rmtakes the list of empty files provided by find and passes them as arguments to the rm command, which removes the files|pipe connects the standard output (stdout) of the command on the left side of the pipe to the standard input (stdin) of the command on the right side
git fetchupdates the remote-tracking branches in your local repository to match the state of the remote repository.- The
-por--pruneoption is used to remove any remote-tracking branches that no longer exist on the remote repository. - This command is used to retrieve the latest changes and objects from the remote repository.
- The
git fsck --fullThis command performs a full object store check in the Git repository.git fsck(file system consistency check) is a command used to check the integrity of the Git repository's object database.- The
--fulloption ensures that all objects are checked, including those that are not reachable from any branch or tag. - The purpose of this line is to verify the integrity of the object store and ensure there are no remaining corruption issues. Overall, these commands aim to fix a broken Git repository by removing empty object files, fetching missing objects from the remote repository, and performing a comprehensive integrity check.
in Short,
- remove any empty object files that cause corruption
- fetch down the missing objects (as well as latest changes)
- do a full object store check
- If Error on
find .git/objects/ -type f -empty | xargs rm
rm: missing operandSo add -r flag in the rm command like
find .git/objects/ -type f -empty | xargs -r rm- If Error on
git fetch -p
error: refs/heads/main does not point to a valid object!
fatal: bad object HEADTry this shell script : Refer
git for-each-ref --format="%(refname)" | while read ref; do
git show-ref --quiet --verify $ref 2>/dev/null || git update-ref -d $ref
doneThis is the safest and most common approach when you explicitly want the feature branch to match main.
Steps :
# Make sure main is up to date
git checkout main
git pull origin main
# Switch to feature branch
git checkout feature-branch
# Force feature branch to match main exactly
git reset --hard origin/main
# if remote exists
git push origin feature-branch --forceResult :
- feature-branch now points to the same commit as main
- Working tree + index are identical
- Conflicts are completely bypassed
Why this works
- Resetting hard moves the branch pointer to main
- Git does not merge → so no conflicts
- History is rewritten so both branches now share the same commit graph
Issue :
The repository was originally cloned as a shallow and likely --single-branch clone (only main).
Because of this:
- Git did not create remote-tracking refs (
origin/<branch>) for other branches. - Running
git fetch origin feature-branchfetched the data only into FETCH_HEAD, not intoorigin/feature-branch. - As a result, git checkout
origin/feature-branchfailed because that ref did not exist locally.
Solution : Explicitly fetch the branch and store it as a remote-tracking branch, then create a local branch from it.
git fetch origin feature-branch:refs/remotes/origin/feature-branch
git checkout -b feature-branch origin/feature-branchWhy this worked :
- The first command manually created origin/feature-branch in the local repo (bypassing --single-branch limitations).
- The second command:
- Created a local branch
- Pointed it to the latest commit on the remote branch
- Set proper upstream tracking
- After this, the branch behaves like a normal Git branch (git pull works as expected).
git initgit remote add origin git@github.com:SSH_LINK.gitgit remotegit statusStatus will show that no commits and untracted files are there excluding the ones which are listed in .gitignore
git add -Agit commit -m "msg"git push -u origin masterHere is a related article which is really good and can be used as Git cheat-sheat too.
