Skip to content

A single place where all I know about using Git and Github can be found.

Notifications You must be signed in to change notification settings

meetmakwana19/about-git

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

77 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Git Cheatsheet

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 update

If the version is equal to or greater than Git 2.16.1(2):

Use command

git update-git-for-windows

1st time git setup

STEP 0.1

git config --global user.name yourname

STEP 0.2

git 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)

STEP 1

(This step is optional is you already have an existing .gitignore file) "touch" creates a new blank file of .gitignore

touch .gitignore

edit the .gitignore file and add the name of the folder which we dont want to upload

STEP 2 - Initialization

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 init

STEP 3 - Staging

Very 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 filename

If want to put all the files of the directory at staging then,

git add -A

If want to put only the modified and deleted items at staging then,

git add -u

To 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

STEP 4 - Commit

  • git commit means taking a snapshot

  • So git add and git commit makes 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 :
    • -a Commits modified and deleted files
    • Remember this following will mostly work when we have done tracking(staging) with the git add command 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.txt
git commit -m "Commiting file1.txt with custom message"

Similarly,

git add file2.txt
git 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 --oneline

Commit done 🎉 , now Push remaining

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
  • Technically, the -u flag 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.

Getting Started with ➡ Github ⬅

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.git

git@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 remote

Output:

origin
  • TO SEE URL
git remote -v

Output :

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 :

  1. Go to this Github documentation by clicking here to generate new ssh key.

  2. Paste the text below, substituting in your GitHub email address.

    ssh-keygen -t ed25519 -C "your_email@example.com"
  3. 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 .ssh folder and try to run the folder command.
    ssh-add ~/.ssh/id_ed25519

If things are not working out check this

  1. To read the ssh key I went to the directory given by previous eval command and opened .pub file with notepad

  2. Copied the ssh key and added it as a new ssh key on Github's Acc settings > SSH Keys > New SSH Key(green button).

  3. Went to repo's "Code" tab and clicked on "Code 🔽" green button and copied ssh url.

  4. Copied the SSH url which looks like git@github.com:meetmakwana19/about-git.git


Using 2 github accounts in one computer (Please Ignore if not needed) :

  • Do all the setps as above by starting with generating ssh keys for another email id like the following :
  1. ssh-keygen -t ed25519 -C "other_email@example.com"
    1. Type the name of new file for saving key with complete path like : C:\Users\meet.makwana/.ssh/id_ed25519_other
    2. Copy paste the public key in your another github account's settings.
  2. eval "$(ssh-agent -s)"
  3. Add that other private key to the ssh-agent : ssh-add ~/.ssh/id_ed25519_other
  4. Now your .ssh/ folder has 2 private 2 public keys for 2 different github accounts.
  5. Make a config file 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
  1. Now change the email id in your required directory for that other github word like git config user.email "other_email@gmail.com"
  2. 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.git

or

git remote set-url origin git@github-other.com:meetmakwana19/about-git.git

Continued :

  1. Have to set the Github's SSH url to the local machine
git remote set-url origin git@github.com:meetmakwana19/about-git.git
  1. 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 ,
  1. git checkout newBranch
  2. git push -u origin

Miscellaneous

1) Directly commit by skipping staging area

git commit -a -m "Skipped staging area and commited directly"

-a is selecting All for stagging and -m is for Message.

2) Remove the file

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.py

Or

1] From only remote repository while keeping the local one untouched.

git rm --cached file1.png file2.txt file3.py

2] Then just commit nd push the changes.

git commit -m "Removed"
git push

3) Shorthand for status

$ 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

4) Clone Command

  1. Making a new folder on PC and opening git bash(by right click menu) over there to clone into that folder.

  2. Will go to any public repository on Github and under code tab will copy the https link.

  3. 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 and meet is 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.

  4. Clone to a specific_branch

    git clone -b specific_branch remote_link_SSH_or_HTTPS

5) Branch

  • 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 branch

SHORTHAND FOR CREATING AND ENTERING(SWITCHING TO IT) THE BRANCH AT THE SAME TIME

git checkout -b newBranch

TO SWITCH TO ANOTHER BRANCH

Meet@LAPTOP ~/OneDrive/Desktop/New folder (master)
$ git checkout feature1

Switched 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.

6) Playing with 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 master branch 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_name

Then after all these or any of these push changes forcibly,

git push -f origin myBranch

7) Logs

TO GET LOG OF ALL OUR COMMITS

git log

TO 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)

8)Compare changes

WILL COMPARE AND SHOW THE DIFFERENCES BETWEEN THE CURRENT FILES(WORKING TREE) AND STAGED FILES

git diff

WILL COMPARE AND SHOW THE DIFFERENCES BETWEEN THE LAST COMMIT AND STAGED FILES

git diff --staged

9) .gitignore

.gitignore file has the list of all the files and folders which we dont want to track with git. SHOULD BE KNOWN :

  1. TO IGNORE ALL THE FILE-TYPES(.log), ADD THIS IS IN .gitignore eg: (.log)

    *.log
  2. TO IGNORE A FOLDER USE A FORWAD SLASH

    `folder_name`/

10) Restore files

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 -f

11) Get the remote repository to local PC

Can make a new folder and run git init by opening git bash in that folder.

git clone https_link
  • Whereas git pull on 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_link

So,

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 repository
  • git remote add origin <remote-url> // add remote
  • git fetch // fetch all remote branchs
  • git 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)

12) Removing Staged files from Staging level

git restore --staged staged_file_name_or_path
git reset staged_file_name_or_path
git reset HEAD staged_file_name_or_path

HEAD 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 reset
git reset HEAD
or
git reset HEAD .
or
git reset HEAD --

Remove commited files from commit level and unstage them without losing changed data :

git reset HEAD~1

Instead of 1, there could be any number of commits you want to unstage.

13) To undo changes in the file at local level :

It's basically Ctrl+Z IMP : But it's different because the file is not yet commited/staged.

git revert file.txt

Or

git checkout -- file.txt

14) Getting back to previous commit

i) To go back to previous commit

revert HEAD reverts the current state(HEAD) to the last commit.

git revert HEAD

ii) To go back to a specific commmit

12abc34 is the 7 digit example git commit ID. To know the git commit IDs of all the commits made.

git log --oneline

Then use that ID for revert command.

git revert 12abc34

After 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 log

Then use that 40 characters long ID for revert command.

git revert 4e28d49dc37b66v755b6f95dc70c8e579z3830f8

The above ID is example and please dont try to copy paste the same ID

Then,

git push

15) git reset - To destroy previous commits

Say 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 :-

1) git reset --hard

--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 4e28d49dc37b66v755b6f95dc70c8e579z3830f8

The 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 myBranch

Need 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.

2) git reset --soft

--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 push or git push -u origin wont work as we want to force push🌝
git push origin +master

Or

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.

Important lesson I learnt

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 reflog

Somewhere 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:

Screenshot

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 85bfa92

This 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.md

Writing the names of all files together to restore them in one go.

16) Rename message of last commit

git commit --amend

After 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.

17) Alter details of previous commits :

If you want to change the dates of multiple commits, you can do so by using an interactive rebase.

  1. Start an Interactive Rebase
    1. Decide how many commits back you want to change. For example, if you want to modify the last 3 commits:
    2. This will open your default text editor with a list of the last 3 commits.
git rebase -i HEAD~3
  1. Edit the Commits

    1. In the editor, you'll see something like this:
    2. 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
    1. Enter i key to enter the insert mode.
    2. Change pick to edit for 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
    1. Save and close the editor by pressing esc key and the typing :wq and press Entern.
  2. Amend Each Commit

    1. 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
    1. For each commit, run:
    git commit --amend --date="YYYY-MM-DDTHH:MM:SS"
    1. This will also open the editor. Save and exit it.
    2. Continue the Rebase. This will move on to the next commit in the rebase sequence.
    git rebase --continue
    1. Edit the Next Commit (If Needed).
  3. Rebase and update the branch after completing all the edit :

git rebase --continue
  1. 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-lease

18) Amend old commit and delete everything above it without losing its content :

If 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:

  1. 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.

  1. Get those staged changes out of staging and make the necessary changes you wished to get in that commit
  2. Stage back all the changes
  3. Amend the commit
git commit --amend

This will update the commit message and include new changes.

  1. Force push the updated commit,

Since this rewrites history, you need to force push:

git push --force-with-lease

19) How to insert image in markdown ?

![alt text for screen readers](/path/to/image.png "Text to show on mouseover")

20) How to color text in markdown ?

<span style="color:yellow">some *yellow* text</span>

21) Stash command

  • 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
    1. Switch to other branch carrying changes to other changes
    2. Git wont allow to switch and will ask to commit/stash the changes
  • The command allows switching branches without commiting to the current branch
  • Stash meaning 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

22) Commit in the past

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"

23) Tags

  • 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: lightweight and annotated.
    • 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 Your Tags :

  • Listing the existing tags in Git is straightforward. Just type git tag (with optional -l or --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*"

Creating Tags :

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 show command:
git show v1.4

Lightweight Tags

  • To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name:
git tag v1.4-lw

Tagging Later :

  • You can also tag commits after you’ve moved past them.
git tag -a v1.2 9fceb02 - m "my version v1.2"

Push tags :

  • 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 --tags option to transfer all the tags.
git push origin --tags
git push --tags

Deleting Tags :

  • On local level
git tag -d v1.4-lw
  • On remote level
git push origin --delete v1.4

24) Rebasing your branch with the base branch

  1. To rebase your branch on the latest main and maintain a linear history, run:
git fetch origin
git rebase origin/main
  1. If there are conflicts, Git will prompt you to resolve them. After resolving, continue rebase with:
git rebase --continue
  1. 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

25) Get back committed changes from commit level to stage level

  • 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.

26) Amend commited changes :

  1. Find the Commit ID
git log --oneline
  1. 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" )

  1. 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 5

Press 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.

  1. Make Changes & Amend the Commit

    1. Now Git will stop at that commit.

    2. Modify your files (if needed)

    3. Stage the changes

    4. Now you can amend the changes with a new commit message or the old one itself

      1. For new message :

        git commit --amend -m "Updated commit message or changes"
        
      2. For old message :

        git commit --amend --no-edit

        or simply

        git commit --amend
    5. Continue the rebase:

      git rebase --continue
  2. Since this rewrites history, force push

git push --force

or if you want a safer force push (only overwriting if you’re up-to-date), use:

git push --force-with-lease

27) Amend commited changes of last commit :

  • 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 :

  1. Make your changes to the file(s) locally.
  2. Stage the changes
  3. Amend the last commit:
git commit --amend

It will open your commit message editor.

You can keep the same message or edit it if you want.

Save and close the editor.

  1. Since this rewrites history, force push
git push --force

or if you want a safer force push (only overwriting if you’re up-to-date), use:

git push --force-with-lease

28) Error : Object file is empty ? .git is corrupt ?

Error 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
  1. Finding empty .git object files and then xargs rm takes the list of empty files provided by find and passes them as arguments to the rm command, which removes the files
    1. | 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
  2. git fetch updates the remote-tracking branches in your local repository to match the state of the remote repository.
    1. The -p or --prune option is used to remove any remote-tracking branches that no longer exist on the remote repository.
    2. This command is used to retrieve the latest changes and objects from the remote repository.
  3. git fsck --full This command performs a full object store check in the Git repository.
    1. git fsck (file system consistency check) is a command used to check the integrity of the Git repository's object database.
    2. The --full option ensures that all objects are checked, including those that are not reachable from any branch or tag.
    3. 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,

  1. remove any empty object files that cause corruption
  2. fetch down the missing objects (as well as latest changes)
  3. do a full object store check
  • If Error on
find .git/objects/ -type f -empty | xargs rm

rm: missing operand

So 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 HEAD

Try 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
done

29) Force a Feature Branch to Match main Exactly (Discard All Conflicts & History)

This 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 --force

Result :

  • 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

30) Switching to a Remote Branch in a Shallow / Single-Branch Clone

Issue : The repository was originally cloned as a shallow and likely --single-branch clone (only main).

Because of this:

  1. Git did not create remote-tracking refs (origin/<branch>) for other branches.
  2. Running git fetch origin feature-branch fetched the data only into FETCH_HEAD, not into origin/feature-branch.
  3. As a result, git checkout origin/feature-branch failed 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-branch

Why 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).

Simple Walkthrough for Pushing

Do the following when understood all of the above steps

Applicable when want to push a local project to a new github repository

git init
git remote add origin git@github.com:SSH_LINK.git
git remote
git status

Status will show that no commits and untracted files are there excluding the ones which are listed in .gitignore

git add -A
git commit -m "msg"
git push -u origin master

Related

Here is a related article which is really good and can be used as Git cheat-sheat too.

javatpoint

About

A single place where all I know about using Git and Github can be found.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •