Git: undo changes

Undoing Local Changes That Have Not Been Committed

If you have made changes that you don’t like, and they have not been committed yet, do as follows:

  1. In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo.
  2. Run git status and you should see the affected file listed.
  3. Run the following command, replacing filename.html with your file path (which you could copy and paste from the git status command):
    • git checkout filename.html
  4. That file has now been reverted to the way it was at the previous commit (before your changes).

Undoing a Specific Commit (That Has Been Pushed)

If you have one specific commit you want to undo, you can revert it as follows:

  1. In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo.
  2. Run git status and make sure you have a clean working tree.
  3. Each commit has a unique hash (which looks something like 2f5451f). You need to find the hash for the commit you want to undo. Here are two places you can see the hash for commits:
    • In the commit history on the GitHub or Bitbucket or website.
    • In your terminal (Terminal, Git Bash, or Windows Command Prompt) run the command git log –oneline
  4. Once you know the hash for the commit you want to undo, run the following command (replacing 2f5451f with your commit’s hash):
    • git revert 2f5451f –no-edit
    • NOTE: The –no-edit option prevents git from asking you to enter in a commit message. If you don’t add that option, you’ll end up in the VIM text editor. To exit VIM, press : to enter command mode, then q for quit, and finally hit Return (Mac) or Enter (Windows).
  5. This will make a new commit that is the opposite of the existing commit, reverting the file(s) to their previous state as if it was never changed.
  6. If working with a remote repo, you can now push those changes:
    • git push

Undoing Your Last Commit (That Has Not Been Pushed)

If you made a mistake on your last commit and have not pushed yet, you can undo it. For example, maybe you added some files and made a commit, and then immediately realized you forgot something. You can undo the commit, and then make a new (correct) commit. This will keep your history cleaner.

  1. In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo.
  2. Run this command:
    • git reset –soft HEAD~
    • TIP: Add a number to the end to undo multiple commits. For example, to undo the last 2 commits (assuming both have not been pushed) run git reset –soft HEAD~2
    • NOTE: git reset –soft HEAD~ is the same as git reset –soft HEAD^ which you may see in Git documentation.
  3. Your latest commit will now be undone. Your changes remain in place, and the files go back to being staged (e.g. with git add) so you can make any additional changes or add any missing files. You can then make a new commit.

Undoing Local Changes That Have Been Committed (But Not Pushed)

If you have made local commits that you don’t like, and they have not been pushed yet you can reset things back to a previous good commit. It will be as if the bad commits never happened. Here’s how:

  1. In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo.
  2. Run git status and make sure you have a clean working tree.
  3. Each commit has a unique hash (which looks something like 2f5451f). You need to find the hash for the last good commit (the one you want to revert back to). Here are two places you can see the hash for commits:
    • In the commit history on the GitHub or Bitbucket or website.
    • In your terminal (Terminal, Git Bash, or Windows Command Prompt) run the command git log –oneline
  4. Once you know the hash for the last good commit (the one you want to revert back to), run the following command (replacing 2f5451f with your commit’s hash):
    • git reset 2f5451f
    • git reset –hard 2f5451f
    • NOTE: If you do git reset the commits will be removed, but the changes will appear as uncommitted, giving you access to the code. This is the safest option, because maybe you wanted some of that code and you can now make changes and new commits that are good. Often though you’ll want to undo the commits and through away the code, which is what git reset –hard does.

Git main commands

git config

Usage: git config –global user.name “[name]”  

Usage: git config –global user.email “[email address]”  

This command sets the author name and email address respectively to be used with your commits.

git init

Usage: git init [repository name]

This command is used to start a new repository.

git clone

Usage: git clone [url]  

This command is used to obtain a repository from an existing URL.

git add

Usage: git add [file]  

This command adds a file to the staging area.

Usage: git add .  

This command adds one or more to the staging area.

git commit

Usage: git commit -m “[ Type in the commit message]”  

This command records or snapshots the file permanently in the version history.

Usage: git commit -a  

This command commits any files you’ve added with the git add command and also commits any files you’ve changed since then.

git diff

Usage: git diff  

This command shows the file differences which are not yet staged.

Usage: git diff –staged 

This command shows the differences between the files in the staging area and the latest version present.

Usage: git diff [first branch] [second branch]  

This command shows the differences between the two branches mentioned.

git reset

Usage: git reset [file]  

This command unstages the file, but it preserves the file contents.

Usage: git reset [commit]  

This command undoes all the commits after the specified commit and preserves the changes locally.

Usage: git reset –hard [commit]  This command discards all history and goes back to the specified commit.

git status

Usage: git status  

This command lists all the files that have to be committed.

git rm

Usage: git rm [file]  

This command deletes the file from your working directory and stages the deletion.

git log

Usage: git log  

This command is used to list the version history for the current branch.

Usage: git log –follow[file]  

This command lists version history for a file, including the renaming of files also.

git show

Usage: git show [commit]  

This command shows the metadata and content changes of the specified commit.

git tag

Usage: git tag [commitID]  

This command is used to give tags to the specified commit.

git branch

Usage: git branch  

This command lists all the local branches in the current repository.

Usage: git branch [branch name]  

This command creates a new branch.

Usage: git branch -d [branch name]  

This command deletes the feature branch.

git checkout

Usage: git checkout [branch name]  

This command is used to switch from one branch to another.

Usage: git checkout -b [branch name]  

This command creates a new branch and also switches to it.

git merge

Usage: git merge [branch name]  

This command merges the specified branch’s history into the current branch.

git remote

Usage: git remote add [variable name] [Remote Server Link]  

This command is used to connect your local repository to the remote server.

git remote -v

This command is used to show all remotes.

git push

Usage: git push [variable name] master  

This command sends the committed changes of master branch to your remote repository.

Usage: git push [variable name] [branch]  

This command sends the branch commits to your remote repository.

Usage: git push –all [variable name]  

This command pushes all branches to your remote repository.

Usage: git push [variable name] :[branch name]  

This command deletes a branch on your remote repository.

git pull

Usage: git pull [Repository Link]  

This command fetches and merges changes on the remote server to your working directory.

git stash

Usage: git stash save  

This command temporarily stores all the modified tracked files.

Usage: git stash pop  

This command restores the most recently stashed files.

Usage: git stash list  

This command lists all stashed changesets.

Usage: git stash drop  

This command discards the most recently stashed changeset.

Treeish and Hashes

Rather than a sequential revision ID, Git marks each commit with a SHA-1 hash that is unique to the person committing the changes, the folders, and the files comprising the changeset. This allows commits to be made independent of any central coordinating server.

A full SHA-1 hash is 40 hex characters:
b0c2c709cf57f3fa6e92ab249427726b7a82d221

To efficiently navigate the history of hashes, several symbolic shorthand notations can be used as listed in the table below. Additionally, any unique sub-portion of the hash can be used. Git will let you know when the characters supplied are not enough to be unique. In most cases, 4-5 characters are sufficient.

TREEISHDEFINITION
HEADThe current committed version
HEAD^, HEAD~1One commit ago
HEAD^^, HEAD~2Two commits ago
HEAD~NN commits ago
RELEASE-1.0User defined tag applied to the code when it was certified for release

The complete set of revision specifications can be viewed by typing:

git help rev-parse

Treeish can be used in combination with all Git commands that accept a specific commit or range of commits.

Examples include:

git log HEAD~3..HEAD

git checkout HEAD^^

git merge RELEASE-1.0 

git diff HEAD^..

Viewing

Daily work calls for strong support of viewing current and historical facts about your repository, often from different, perhaps even orthogonal points of view. Git satisfies those demands in spades.

Status

To check the current status of a project’s local directories and files (modified, new, deleted, or untracked) invoke the status command:

git status

Diff

A patch-style view of the difference between the currently edited and committed files, or any two points in the past can easily be summoned. The .. operator signifies a range is being provided. An omitted second element in the range implies a destination of the current committed state, also known as HEAD:

git diff

git diff 32d4

git diff --summary 32d4..

Depending on the Git distribution, a utility called diff-highlight will be included to make diffs easier to visualize by highlighting word-level diffs instead of the default line level changes. Make sure diff-highlight is available in your $PATH and enable it with:

git config --global core.pager "diff-highlight | less -r"

Git allows for diffing between the local files, the stage files, and the committed files with a great deal of precision.

COMMANDDEFINITION
git diffEverything unstaged (not git add’ed) diffed to the last commit
git diff –cachedEverything staged (git add’ed) diffed to the last commit
git diff HEADEverything unstaged and staged diffed to the last commit

Log

The full list of changes since the beginning of time, or optionally, since a certain date is right at your fingertips, even when disconnected from all networks:

git log
git log --since=yesterday $ git log --since=2weeks

Blame

If trying to discover why and when a certain line was added, cut to the chase and have Git annotate each line of a source file with the name and date it was last modified:

git blame <filename.ext>

GIT Overwrite Master with branch

You should be able to use the “ours” merge strategy to overwrite master with develop branch like this:

git checkout develop
git merge -s ours master
git checkout master
git merge develop

The result should be your master is now essentially develop.

(-s ours is short for --strategy=ours)

From the docs about the ‘ours’ strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

GIT SSL certificate problem: unable to get local issuer certificate

Solution 1 (worst): disable certificate in GTI configuration

 git config --global http.sslCAinfo /bin/curl-ca-bundle.crt

Solution 2: if this problem is occuring because git cannot complete the https handshake with the git server were the repository you are trying to access is present.

Steps to get the certificate from the github server

  1. Open the github you are trying to access in the browser
  2. Press on the lock icon in the address bar > click on ‘certicicate’
  3. Go to ‘Certification Path’ tab > select the top most node in the heirarchy of certifcates > click on ‘view certificate’
  4. Now click on ‘Details’ and click on ‘Copy to File..’ > Click ‘Next’ > Select ‘Base 64 encoded X509 (.CER)’ > save it to any of your desired path.

Steps to add the certificate to local git certificate store

  1. Now open the certicate you saved in the notepad and copy the content along with –Begin Certificate– and –end certificate–
  2. To find the path were all the certificates are stored for your git, execute the following command in cmd.git config –list
  3. Check for the key ‘http.sslcainfo’, the correspondig value will be path.
  4. Now open ‘ca-bundle.crt’ present in that path.

Note 1 : open this file administrator mode otherwise you will not be able to save it after update. (Tip – you can use Notepad++ for this purpose)

Note 2 : Before modifying this file please keep a backup elsewhere.

  1. Now copy the contents of file mentioned in step 1 to the file in step 4 at end file, like how other certificates are placed in ca-bundle.crt.
  2. Now open a new terminal and now you should be able to perform opertions related to the git server using https.

To know where gitconfig file is:

git config --list --show-origin

Reset a single file to a specific commit

Assuming the hash of the commit you want is c5f567:

git checkout c5f567 -- file1/to/restore file2/to/restore

The git checkout man page gives more information.

If you want to revert to the commit before c5f567, append ~1 (where 1 is the number of commits you want to go back, it can be anything):

git checkout c5f567~1 -- file1/to/restore file2/to/restore

As a side note, I’ve always been uncomfortable with this command because it’s used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).

Git workflow

Here you can see the basics workflow for git
After cloning your repo from any git platform provider Like github, gitlab, bitbucket etc… .
Firstly check branch:
git branch
(your base branch, most likely develop or master. Consider develop as a base branch)
Fetch latest remote code to local:
git pull
(for latest develop code)
Checkout new branch as per feature and
git checkout -b newBranchName
(If you are working on any new bug named branch feature than give branch name feature/ login-feature or you are working on any bug than give branch name bug/login-bug.
This way you can eaisily identify/judge your branch by name.)

After finish your work in your
$ git status (after Changes )
Add changed file into staging
git add . | | $ git add .. (dot) (for feature/bug branch.(in red colored) add file in staging)
Check staging file (in green colored)
$ git status
Add commit message
$ git commit -m Commit message
Checkout your base branch
$ git checkout develop (switch
For latest code (if other guy
$ git pull (for latest develop code)
Checkout your previous feature/to develop) working on it)
bug branch

git pull (for latest develop code)
Checkout your previous feature.
git checkout YOUR PREVIOUS_BRANCH
Rebase your branch with develop
git rebase develop
Push your feature/bug branch
git push
(it will suggest command if bug branch or master to remote: its not in remote).
After this open your git platform provider Like github, gitlab, bitbucket whatever you use.
Assign merge request to your other develop to review code, it will increase your productivity and code quality.

Git update and publish

git remote -v
git remote show
git remote add
git fetch
git fetch --all
git pull | git pull
git push
git push
git push origin :old-name new-name
git push origin -u new-name
git branch -dr
git push origin YourTagVersion