Git Revision Questions Before the Interview


Git Revision Article Banner

Hello there! This is a consolidated quick revision notes for the topic Git.

Note: The questions are arranged in chronological order so that you can learn the topics in a natural learning curve way! You can treat this as a tutorial cum-notes.


1. What is Git

  • Free Open-Source Distributed Version Control System (DVCS)
  • Developed by Linus Torvalds in the year 2005
  • Also called a Source Control System.

2. Why use Git?

  • Help collaboration among programmers during software development.
  • Track code changes by maintaining the version history of project related files.
  • Helps to automate Continuous Integration (CI) and Continues Development (CD) pipelines for DevOps.

3. Difference between Git and CVS

Sr.No. Git CVS
1 No full form for Git (read more of its naming - wiki link Full Form: Concurrent Versions System
2 Developed by Linus Torvalds Developed by Dick Grune
3 First Release: Year 2005 First Release: Year 1986
4 Distributed Version Control System. Centralized, Client-Server based Version Control System.
5 GNU General Public License version 2.0 GNU General Public License
6 Works Offline. Does not Work Offline.
7 Have a full history of changes stored locally. Does not have a full history of changes stored locally.
8 Commits happen at the local repository. Commits happen at the central server.
9 > 94% market share as of Jan-2023. < 1% market share as of Jan-2023

4. Difference between Git and SVN

Sr.No. Git SVN
1 No full form for Git (read more of its naming - wiki link Full Form: Subversion
2 Developed by Linus Torvalds Developed by Apache Software Foundation
3 First Release: Year 2005 First Release: Year 2000
4 Distributed Version Control System. Centralized, Client-Server based Version Control System.
5 GNU General Public License version 2.0 Apache License
6 Works Offline. Does not Work Offline.
7 Have a full history of changes stored locally. Does not have a full history of changes stored locally.
8 Commits happen at the local repository. Commits happen at the central server.
9 Branching is light-weight process. Branching is heavy-weight process.
10 Users have a copy of the full repository. Users have a copy of just trunk.
11 Difficult to learn. Easy to learn.
12 Not good at handling large binary files. Handles large binary files effectively.
13 Faster commits (as happens on the local repo) Slower commits (as happens on the remote server)
14 Easy to recover even if server crashes (each user has a copy) Single point of failure, if the server crashes, users cannot commit code.
15 > 94% market share as of Jan-2023. < 5% market share as of Jan-2023

5. What is the Market Share of Git and Other VCS

  • Git - 94%
  • SVN - 5%
  • Mercurial - 1%
  • CVS - 0%
  • None - 4%

6. How to check the installed git version?

  • To know the version of Git installed, you can either use the command version or make use of the options -v or --version

    Example 1: Using version command
    # git version
      git version 2.37.2

    Example 2: Using a short option (flag)
    # git -v
      git version 2.37.2

    Example 3: Using long option (flag)
    % git --version
      git version 2.37.1 (Apple Git-137.1)

7. How to get help for Git Commands?

  • Just like version, help is also a command and a option.

    Git help command syntax:

    git help <command-name>


    Examples:
    # git help rm
    GIT-RM(1)                                  Git Manual                                 GIT-RM(1)
    
    git-rm - Remove files from the working tree and from the index
    
    ....
    # git help status
    
    GIT-STATUS(1)                              Git Manual                             GIT-STATUS(1)
    
    NAME
           git-status - Show the working tree status
    
    SYNOPSIS
           git status [<options>...] [--] [<pathspec>...]
    ....


    Git help options: -h or --help flag

    To get help on a command, make use of the option -h (sort option) or --help (long-form) along with the git command that you need help.

    Syntax:

    git -h|--help <command>

    Example:
    # git -h status
    # git --help mv

8. How to get a list of all commands in git?

  • Make use of the git help command with --all flag.
    # git help --all
    
    
     Main Porcelain Commands
       add                  Add file contents to the index
       am                   Apply a series of patches from a mailbox
       archive              Create an archive of files from a named tree
       bisect               Use binary search to find the commit that introduced a bug
       branch               List, create, or delete branches
       bundle               Move objects and refs by archive
       checkout             Switch branches or restore working tree files
       cherry-pick          Apply the changes introduced by some existing commits
       citool               Graphical alternative to git-commit
       clean                Remove untracked files from the working tree
       clone                Clone a repository into a new directory
       commit               Record changes to the repository
       describe             Give an object a human-readable name based on an available ref
       diff                 Show changes between commits, commit and working tree, etc
       fetch                Download objects and refs from another repository
       format-patch         Prepare patches for e-mail submission
       gc                   Cleanup unnecessary files and optimize the local repository
       gitk                 The Git repository browser
       grep                 Print lines matching a pattern
       gui                  A portable graphical interface to Git
       init                 Create an empty Git repository or reinitialize an existing one
       log                  Show commit logs
       maintenance          Run tasks to optimize Git repository data
       merge                Join two or more development histories together
       mv                   Move or rename a file, a directory, or a symlink
       notes                Add or inspect object notes
       pull                 Fetch from and integrate with another repository or a local branch
       push                 Update remote refs along with associated objects
       range-diff           Compare two commit ranges (e.g. two versions of a branch)
       rebase               Reapply commits on top of another base tip
       reset                Reset current HEAD to the specified state
       restore              Restore working tree files
       revert               Revert some existing commits
       rm                   Remove files from the working tree and from the index
       shortlog             Summarize 'git log' output
       show                 Show various types of objects
       sparse-checkout      Reduce your working tree to a subset of tracked files
       stash                Stash the changes in a dirty working directory away
       status               Show the working tree status
       submodule            Initialize, update or inspect submodules
       switch               Switch branches
       tag                  Create, list, delete or verify a tag object signed with GPG
       worktree             Manage multiple working trees
    
    Ancillary Commands / Manipulators
       config               Get and set repository or global options
       fast-export          Git data exporter
       fast-import          Backend for fast Git data importers
       filter-branch        Rewrite branches
       mergetool            Run merge conflict resolution tools to resolve merge conflicts
       pack-refs            Pack heads and tags for efficient repository access
       prune                Prune all unreachable objects from the object database
       reflog               Manage reflog information
       remote               Manage set of tracked repositories
       repack               Pack unpacked objects in a repository
       replace              Create, list, delete refs to replace objects
    
    Ancillary Commands / Interrogators
       annotate             Annotate file lines with commit information
       blame                Show what revision and author last modified each line of a file
       bugreport            Collect information for user to file a bug report
       count-objects        Count unpacked number of objects and their disk consumption
       difftool             Show changes using common diff tools
       fsck                 Verifies the connectivity and validity of the objects in the database
       gitweb               Git web interface (web frontend to Git repositories)
       help                 Display help information about Git
       instaweb             Instantly browse your working repository in gitweb
       merge-tree           Show three-way merge without touching index
       rerere               Reuse recorded resolution of conflicted merges
       show-branch          Show branches and their commits
       verify-commit        Check the GPG signature of commits
       verify-tag           Check the GPG signature of tags
       whatchanged          Show logs with difference each commit introduces
    
    Interacting with Others
       archimport           Import a GNU Arch repository into Git
       cvsexportcommit      Export a single commit to a CVS checkout
       cvsimport            Salvage your data out of another SCM people love to hate
       cvsserver            A CVS server emulator for Git
       imap-send            Send a collection of patches from stdin to an IMAP folder
       p4                   Import from and submit to Perforce repositories
       quiltimport          Applies a quilt patchset onto the current branch
       request-pull         Generates a summary of pending changes
       send-email           Send a collection of patches as emails
       svn                  Bidirectional operation between a Subversion repository and Git
    
    Low-level Commands / Manipulators
       apply                Apply a patch to files and/or to the index
       checkout-index       Copy files from the index to the working tree
       commit-graph         Write and verify Git commit-graph files
       commit-tree          Create a new commit object
       hash-object          Compute object ID and optionally creates a blob from a file
       index-pack           Build pack index file for an existing packed archive
       merge-file           Run a three-way file merge
       merge-index          Run a merge for files needing merging
       mktag                Creates a tag object with extra validation
       mktree               Build a tree-object from ls-tree formatted text
       multi-pack-index     Write and verify multi-pack-indexes
       pack-objects         Create a packed archive of objects
       prune-packed         Remove extra objects that are already in pack files
       read-tree            Reads tree information into the index
       symbolic-ref         Read, modify and delete symbolic refs
       unpack-objects       Unpack objects from a packed archive
       update-index         Register file contents in the working tree to the index
       update-ref           Update the object name stored in a ref safely
       write-tree           Create a tree object from the current index
    
    Low-level Commands / Interrogators
       cat-file             Provide content or type and size information for repository objects
       cherry               Find commits yet to be applied to upstream
       diff-files           Compares files in the working tree and the index
       diff-index           Compare a tree to the working tree or index
       diff-tree            Compares the content and mode of blobs found via two tree objects
       for-each-ref         Output information on each ref
       for-each-repo        Run a Git command on a list of repositories
       get-tar-commit-id    Extract commit ID from an archive created using git-archive
       ls-files             Show information about files in the index and the working tree
       ls-remote            List references in a remote repository
       ls-tree              List the contents of a tree object
       merge-base           Find as good common ancestors as possible for a merge
       name-rev             Find symbolic names for given revs
       pack-redundant       Find redundant pack files
       rev-list             Lists commit objects in reverse chronological order
       rev-parse            Pick out and massage parameters
       show-index           Show packed archive index
       show-ref             List references in a local repository
       unpack-file          Creates a temporary file with a blob's contents
       var                  Show a Git logical variable
       verify-pack          Validate packed Git archive files
    
    Low-level Commands / Syncing Repositories
       daemon               A really simple server for Git repositories
       fetch-pack           Receive missing objects from another repository
       http-backend         Server side implementation of Git over HTTP
       send-pack            Push objects over Git protocol to another repository
       update-server-info   Update auxiliary info file to help dumb servers
    
    Low-level Commands / Internal Helpers
       check-attr           Display gitattributes information
       check-ignore         Debug gitignore / exclude files
       check-mailmap        Show canonical names and email addresses of contacts
       check-ref-format     Ensures that a reference name is well formed
       column               Display data in columns
       credential           Retrieve and store user credentials
       credential-cache     Helper to temporarily store passwords in memory
       credential-store     Helper to store credentials on disk
       fmt-merge-msg        Produce a merge commit message
       hook                 Run git hooks
       interpret-trailers   Add or parse structured information in commit messages
       mailinfo             Extracts patch and authorship from a single e-mail message
       mailsplit            Simple UNIX mbox splitter program
       merge-one-file       The standard helper program to use with git-merge-index
       patch-id             Compute unique ID for a patch
       sh-i18n              Git's i18n setup code for shell scripts
       sh-setup             Common Git shell script setup code
       stripspace           Remove unnecessary whitespace

9. What is Git Working Directory? How to create a git repository?

  • A Working Directory a directory that contains your project files and folders that you want to be managed by git as a repository.

    All your project files and folders remains in working directory until you add them to the Staging Area using git add command.

    To create a git repository,

    1. Create a folder on your device, or move to your project folder (working directory),
    2. Open the folder location using Terminal/CMD/Git Bash,
    3. Now run the command git init
    4. Now a .git hidden folder will be created inside the working directory which is your project repository.
    Example:
    # mkdir myrepo
    # cd myrepo
    # git init
    Initialized empty Git repository in /Users/code2care/Desktop/myrepo/.git/

10. What is git init command?

  • git init command is used to create an empty Git repository or reinitialize an existing one.

    Using the init command one can convert a directory into a git-managed repository (working directory)

    Once you run the git init command, a hidden .git directory is created that contains files and folders used to manage your repository.


11. What happens if you run the git init for a existing repository?

  • It is safe to run git init command for a already existing repository, it will not result in overwriting of contents that are already existing .git folder.


12. How can you see the .git folder?

  • Use Git Bash (Windows) or Terminal (macOS/Linux) and move to your local repository, run the command ls -la
    # ls -la
    total 0
    drwxr-xr-x   4 code2care  staff  128 Jan  4 00:11 .
    drwx------@ 22 code2care  staff  704 Jan  3 23:38 ..
    drwxr-xr-x   9 code2care  staff  288 Jan  3 23:38 .git
    -rw-r--r--   1 code2care  staff    0 Jan  4 00:11 README.txt

13. What is git config command?

    config is a command used to manage files that store git configurations, there are three files that are used to define configurations at three different levels,

    1. Local: config
    2. Global: .gitconfig
    3. System: /etc/gitconfig

    The git config command is used to query, set, replace, unset local, global or system options.


14. What is the git local config file? How to see its set options?

    The git config local file is the current repository config file that contains options (configurations) that are applicable to the local repository.

    The local config file is located inside the repo/.git/config

    # cat myrepo/.git/config 
    
    [core]
    	repositoryformatversion = 0
    	filemode = true
    	bare = false
    	logallrefupdates = true
    	ignorecase = true
    	precomposeunicode = true

    To see the list of set options in the local config file use the config command with --list, --show-scope and --local options.

    Example:
    # git config --list --show-origin --show-scope --local
      local   file:.git/config        core.repositoryformatversion=0
      local   file:.git/config        core.filemode=true
      local   file:.git/config        core.bare=false
      local   file:.git/config        core.logallrefupdates=true
      local   file:.git/config        core.ignorecase=true
      local   file:.git/config        core.precomposeunicode=true

15. What is the git Global Config file? How to see its set options?

  • The Git Global Config is a configuration file that is used to write user-specific configurations (logged-in user).

    The global config file can be found under:

    Mac/Linux:
    /Users/username/.gitconfig (~/.gitconfig)
    Windows:
    C:\<user-folder>\.gitconfig
    Example: To see contents of Git Global config file
    # git config --list --show-origin --show-scope --global
      global  file:/Users/code2care/.gitconfig        user.name=student
      global  file:/Users/code2care/.gitconfig        user.email=dummy@dummy.com
    # cat ~/.gitconfig 
    
    [user]
    	name = student
    	email = dummy@dummy.com

16. What is Git Config System file? How to see its contents?

  • The git config system file is the file that is used to store git configurations that is applicable to all users (at the system level) and their repositories.

    Note: Administrative or superuser (sudo) privileges are required to make changes at the system level.

    The file is located at:

    Mac/Linux:
    /etc/gitconfig
    Windows:
    C:\Documents and Settings\All Users\Application Data\Git\config
    Examples:
    # git config --list --show-origin --show-scope --system
      system  file:/etc/gitconfig     env.isstage=true
    # cat /etc/gitconfig
     [env]
    	isStage = true

17. How to see a list of all git config options?

  • Make use of the git config command with --list option.

    # git config --list --show-origin --show-scope
     system  file:/etc/gitconfig     env.isstage=true
     global  file:/Users/code2care/.gitconfig        user.name=student
     global  file:/Users/code2care/.gitconfig        user.email=dummy@dummy.com
     local   file:.git/config        core.repositoryformatversion=0
     local   file:.git/config        core.filemode=true
     local   file:.git/config        core.bare=false
     local   file:.git/config        core.logallrefupdates=true
     local   file:.git/config        core.ignorecase=true
     local   file:.git/config        core.precomposeunicode=true

18. How to set (add) a configuration option?

  • Syntax:
    git config --[global|local|system] section.variable value
    Examples:
    # git config --local demo.env local
    # git config --global demo.env global
    # git config --system demo.env system

    We can also make use of the --add flag to add multiple lines to an option.

    Example:
    # git config --local --add demo.name myproj

19. How to view a specific configuration option?

  • Syntax:
    git config --[global|local|system] section.variable
    Example:
    # git config --local core.filemode
      true

    It can be so that a specific option is set for all multiple scopes, making use of the --get-all flag to look at all scopes,

    Example:
    # git config --show-origin --get-all demo.msg
    file:/etc/gitconfig     hello-local
    file:/Users/code2care/.gitconfig        hello-global
    file:.git/config        hello-system

20. How to delete (remove/unset) a specific configuration option?

  • Make use of the --unset flag to delete a config option.

    Syntax:
    git config --[global|local|system] --unset section.variable
    Example:
    # git config --unset --local app.env

21. How to edit a specific configuration file?

  • Make use of the --eidt flag to edit a config option.

    Syntax:
    git config --[global|local|system] --edit
    Example:
    # git config --edit --local

    This will open the file in the default text editor (or one that you have set for git) vim/nano etc where you can edit the config file and then save changes.


22. What is the default scope of the git config command?

  • --local is the default scope for the git config command. All commands options you use with the git config command without passing the scope will be executed on the local config file.

    Example: --list, set and --unset will all be run against the default local config
    # git config demo.test test
    
    # git config --list --show-scope
    ..
    ..
    local   demo.test=test
    
    # git config --unset demo.test

23. How to set a boolean value option?

  • Make use of the --bool flag.

    Example:
    # git config --local --bool env.disabled false

24. How to find a git config option using regular expression?

  • Make use of the --get-regex flag to find a config option to search using a regular expression,

    # git config --get-regex core
    core.repositoryformatversion 0
    core.filemode true
    core.bare false
    core.logallrefupdates true
    core.ignorecase true
    core.precomposeunicode true

25. How to find a git config option that matches a URL?

  • Make use of the option --get-urlmatch to get a list of all URLs that matches the provided url


26. Get the list of all of the config variables (options)?

  • Make use of the command git help --config

    # git help --config
    
    add.ignoreErrors
    ...
    ...
    worktree.guessRemote

27. If the same variable is set at all local, global, and system levels which will get referred?

  • The precedence is always given to the System level variables.

    Its System -> Global -> Local


28. How to set the user and email at the global level config file?

  • # git config --global user.name "Your Name"
    # git config --global user.email "your-email@domain.com"

29. How to set your custom editor for git?

  • Example: emacs
    # git config --global core.editor emacs
    Example: nano
    % git config --global core.editor "nano -w"
    Example: Notepad++
    # git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

30. How to set the name of the default branch as main instead of master?

  • # sudo git config --global init.defaultBranch main

31. What is Staging Area in Git?

  • When you run the git add command on a file or set of files, the file(s) gets added to the staging area, and the file(s) get indexed and tracked by git repostiory.


32. How to add a file to Staging Area?

  • To add a file in the staging area, run the git add command followed by the file name from the working directory.

    Example:
    # mkdir myrepo
    # cd myrepo
    # touch myfile.txt
    
    # git add myfile.txt

33. How to add all files from the Working directory to Staging Area?

  • Run the command git add . to add all files from the working directory to the git staging area.

    Example:
    # touch Class1.java
    # touch Class2.java
    # touch Class3.java
    
    # git add .

34. How to add all files to Staging Area using regular expressions?

  • Example:
    # touch Class1.java
    # touch Class2.java
    # touch Class3.txt
    
    # git add *.java

    The above example will only add the file with the .java extension to the staging area.


35. How to check the status of all files in the Git Working Directory?

  • To know the status of files in the git working directory, make use of the git status command.

    Example:
    # git status
    
    On branch main
    Changes to be committed:
      (use "git restore --staged <file>..." to unstage)
    	new file:   Class3.java
    
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git restore <file>..." to discard changes in working directory)
    	modified:   Class2.java
    
    Untracked files:
      (use "git add <file>..." to include in what will be committed)
    	Class1.java

36. How to know the git status in short form?

  • Use the flag --short or -s along with the git status command,

    Example:
    # git status --short
    
    status --short
     M Class2.java
    A  Class3.java
    ?? Class4.java

37. What are the different stages a file can be in Git?

  • A -> Added
    ' ' -> Unmodified
    M -> Modified
    U -> Updated but unmerged
    D -> Deleted
    R -> Renamed
    T -> File type changed
    C -> Copied
    ?  -> Untracked
    !   -> Ignored

38. Explain the lifecycle of a file (states a file can be in)?

Git Lifecycle of a file stages

39. What is index in Git?

  • The index is an area that's between your Working Directory and Local Repository. The index is also known as the Staging Area.

    When you run the git add command the files get indexed (added) from the Working Directory to the Staging Area.

    The files are said to "tracked" or "indexed" when you run the git add command.

    Note: Files are not moved or copied but get indexed and details are stored in a binary file called index which you can locate under your-repo/.git/index


40. What is Staging Area in Git?

  • The Staging area is where you add the files once ready to be committed to your local repository.

    Once you reach a milestone on something that you are working on, you should run the git add command to index your files.

    The details of the files staged are stored in a file under your-repo/.git/index


41. Explain the terms Working Directory, Staging Area and Local Repository, and Remote Repository in Git?

  1. Working Directory: Working directory is the project that you actually work on. A directory containing files and folders that you want to be managed by Git as a repository. Files in the working directory are said to be Untracked (not managed by Git) until you run the git add command to get them indexed and moved to Staging Area.
  2. Staging Area: This is the area where you add the files once ready to be committed to your local repository. The files in the Staging area are said to be "Tracked" or "Indexed" and are managed by Git. If you modify a file after adding it to the Staging area they are said to be in "Modified" status. The details of the files indexed are stored in a file under your-repo/.git/index
  3. Local Repository: When you run the git commit command the files get moved from the Staging area to the Local Repository. The local repository maintains a version of all commits as objects under your-repo/.git/objects folder.
  4. Remote Repository: All commits in Git happens on the Local Repository. When you run the git push command the local repository (branch actually) is moved from your local computer to your git server called a remote repository (e.g. GitHub, GitLab or Bitbucket)
Git Working Directory - Staging Area - Local and Remote Repository Diagram

42. What is a Working tree?

  • Working tree is nothing but another name for Working Area.


43. How to perform a commit to a local Git repository?

  • Make use of the command git commit

    Example:
    $ git commit -m "Initial Commit"
     1 file changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 Samle.py

44. Which flag is to be used for adding a commit comment?

  • Make use of the -m or --message flag to add a commit comment or message.

    Example:
    $ git commit -m "Some comment"

45. How to commit directly by skipping Staging Area?

  • Make use of the -a or --all flag along with the git commit command.

    Note this only works on the files that are already tracked by git.

    Example:
    $ echo "Some text" >> Sample.py
    $ git commit -a -m "direct commit"
     1 file changed, 1 insertion(+)

46. How to dry run a commit command?

  • Make use of the flag --dry-run along with the git commit command.

    Example:
    $ git commit --dry-run
    On branch main
    Changes to be committed:
     (use "git restore --staged <file>..." to unstage)
    	new file:  Main.py
    	modified file:  Sample.py

47. How to set a custom date and time to git commit?

  • Make use of the --date flag.

    Example:
    $ git commit -m "Some comment" --date "Thu 5 Jan 2023 01:30:00 PST"

48. How to see the Git Repository Commit Logs?

  • git log is the command to be used to see the commit log details.

    Example:
    $ git log
    commit 1e7be1e7feff67cf993eee896b7d346a7b3d7ce9 (HEAD -> main)
    Author: Code2care <code2care@Code2care-Air.local>
    Date:   Thu Jan 5 14:40:32 2023 -0500
    
        Commit 2
    
    commit 3291fc958ebd87d44f3bda0ba4d22aab8a83597a
    Author: Code2care <code2care@Code2care-Air.local>
    Date:   Thu Jan 5 12:59:51 2023 -0500
    
        Commit 1

49. How to see git commit logs as one per line?

  • Make use of the flag --oneline

    $ git log --oneline
    1e7be1e (HEAD -> main) Commit 2
    3291fc9 Commit 1

50. What is the Git Reset command?

  • reset is the command in git used to reset the current HEAD to the specified state.

    reset is like a undo operation that can be performed on the git commits to moving the HEAD.

    Git reset command example diagram

51. What are the different modes of reset commands?

  • There are 5 modes,

    1. --soft: Does not touch the index file or the working tree.
    2. --mixed: This is the default mode. Resets the index but not the working tree
    3. --hard: Resets the index and working tree.
    4. --merge: Resets the index and updates the files in the working tree that are different between commit and HEAD
    5. --keep: Resets index entries and updates files in the working tree that are different between commit and HEAD.

    Note: --soft, --mixed, --hard are the most commonly used modes.


52. Provide examples of Git reset

  • $ touch Sample1.py Sample2.py
    $ git add File1.txt
    $ git commit -m "Code Commit 1"
    
    $ git add File2.txt
    $ git commit -m "Code Commit 2"
    
    $ git log --oneline 
    341ab47 (HEAD -> main) Code Commit 2
    3291fc9 Code Commit 1

    Hard Reset Example:
    $ git reset --hard 3291fc9
    HEAD is now at 3291fc9 Code Commit 1
    
    $ ls
    Sample1.py
    
    $ git status
    On branch main
    nothing to commit, working tree clean

    Mixed Reset Example:
    $ git reset --mixed 3291fc9
    
    $ ls
    Sample1.py  Sample2.py
    
    $ git status
    On branch main
    Changes to be committed:
      (use "git restore --staged ..." to unstage)
    	new file:   Sample2.py

    Soft Reset Example:
    $ git reset --mixed HEAD^1
    
    $ ls
    Sample1.py  Sample2.py
    
    $ git status
    On branch main
    Untracked files:
      (use "git add ..." to include in what will be committed)
    	Sample2.py
    
    nothing was added to commit but untracked files are present

53. How to restore staged area files back to the Working directory?

  • If there were modifications made to the indexed files or new files were added to the git staging area or both. You can restore them back to the working area using the git restore command.

    Example:
    $ git status
    On branch main
    Changes to be committed:
      (use "git restore --staged <file>..." to unstage)
    	modified:   File1.txt
    	new file:   File2.txt

    There are two files in the staging area - one is modified and another is a new file. We can restore them back to the working directory as below,

    $ git restore --staged File1.txt File2.txt
    $ git status
    On branch main
    Changes not staged for commit:
      (use "git add &tl;file>..." to update what will be committed)
      (use "git restore <file>..." to discard changes in working directory)
    	modified:   File1.txt
    
    Untracked files:
      (use "git add &tl;file>..." to include in what will be committed)
    	File2.txt
    
    no changes added to commit (use "git add" and/or "git commit -a")

53. How to restore all files at once from the Staging area (index)?

  • $ git restore --staged .

    Make use of . (dot) to restore all.


54. What is the revert command used for?

  • The git revert command is an undo command just like the reset command, but the difference is, instead of completely removing all commits ahead of the commit, it takes the commit to revert and creates a new commit and points the HEAD to it.

    Git Revert Command with Example

55. Give Example of Git Revert Command.

  • $ touch Class1.java Class2.java
    $ git add Class1.java
    $ git commit -m "Commit 1"
    
    $ git add Class2.java
    $ git commit -m "Commit 2"
    
    $ git log --oneline
    08086b7 (HEAD -> main) Commit 2
    caeb6fa Commit 1
    $ git revert caeb6fa
    $ ls
    Class1.java
    
    $ git status
    On branch main
    nothing to commit, working tree clean
    
    $ git log --oneline
    4abdb83 (HEAD -> main) Reverted "Commit 1"
    08086b7 Commit 2
    caeb6fa Commit 1

56. What is the difference between reset and revert command?

  • Sr.No. Revert Reset
    1
    Git Revert Command with Example
    Git reset command example diagram
    2 Does not modify commit history. Modifies commit history.
    3 New commit is created. No new commit is created.
    4 Safe way to undo commit history. Risky way to undo commit history.
    5 Ideally used with the remote repositories. Ideally used with the local repositories.

57. What is the command rebase used for? Give an example

  • rebase is a command used for integrating changes from one branch onto another.

    rebase is command is similar to merge command, but merge is only forward moving.

    rebasing helps to maintain a linear and a clean project history.

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap