The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • git status
  • Description
  • Usage
  • What It Shows
  • Example Output
  • Common Workflow
  • git diff
  • Description
  • Usage
  • Basic Use Cases
  • Example Output
  • git add
  • Description
  • Usage
  • What It Does
  • Common Use Cases
  • Example Output
  • git rm
  • Description
  • Usage
  • What It Does
  • Common Use Cases
  • Example Workflow
  • Example Output
  • git commit
  • Description
  • Usage
  • What It Does
  • Common Use Cases
  • Example Workflow
  • Example Output

Was this helpful?

  1. Git
  2. Commands

Tracking Changes

git status

Description

It is used to display the state of the working directory and the staging area. It shows which changes have been staged, which haven't, and which files aren't being tracked by Git. This command is very useful for getting a quick overview of the current status of the repository.

Usage

git status [<options>]

Options

-s or --short : It gives the output in a more concise, short format.

Example short format output:

M file3.txt
?? file4.txt

M indicates a modified file. ?? indicates an untracked file.

-b or --branch: Shows the branch and tracking information in a short format.

git status -s
git status -b

What It Shows

  • Untracked Files: Files in your working directory that aren't tracked by Git.

  • Tracked Files: Files that are tracked by Git and have changes that haven't been staged yet.

  • Staged Changes: Files that have changes staged for the next commit.

  • Branch Information: The current branch you are on and whether your local branch is ahead, behind, or has diverged from the remote branch.

Status Indication: git status provides hints on what to do next, such as commands to stage files, unstage files, or discard changes.

Performance: git status can be slow in large repositories because it checks the entire working directory. In such cases, using git status -uno (show untracked files only) might improve performance.

Example Output

Here’s an example of what git status might display

Or

On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   file1.txt
        new file:   file2.txt

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:   file3.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        file4.txt

Breakdown of Example Output

  • Branch Information:

    • On branch main: Indicates the current branch.

    • Your branch is up to date with 'origin/main'.: Shows synchronization status with the remote branch.

  • Staged Changes (Changes to be committed):

    • modified: file1.txt: file1.txt has been modified and staged.

    • new file: file2.txt: file2.txt is a new file that has been staged.

  • Changes Not Staged for Commit:

    • modified: file3.txt: file3.txt has been modified but not staged.

  • Untracked Files:

    • file4.txt: file4.txt is a new file that isn't being tracked by Git.

Common Workflow

-- Check Status
git status

-- Stage Changes
git add file3.txt

-- Check Status Again
git status

-- Commit Staged Changes
git commit -m "Modify file3.txt"

-- Check Status After Commit
git status

git diff

Description

The git diff command is used to show changes between commits, commit and working tree, etc. It is a powerful tool for inspecting the differences between various states of a repository.

By default, git diff shows the differences in the command-line interface. However, it is also possible to use tools like graphical diff viewers to make it easier to review changes. For example, git difftool can be used to open a graphical diff viewer, such as Beyond Compare or KDiff3 or meld etc.

Usage

git diff [<options>] [<commit>] [--] [<path>...]

Options

  • --staged or --cached: Compare the staged changes with the last commit.

  • --name-only: Show only the names of changed files.

  • --name-status: Show the names and status of changed files.

  • -p or --patch: Generate patch (standard output format).

  • --stat: Show a summary of changes

  • -U<n> or --unified=<n>: Generate diffs with <n> lines of context.

  • --color: Colorize the diff output.

git diff --staged
git diff --name-only
git diff --name-status
git diff -p
git diff --stat
git diff -U3
git diff --color

Basic Use Cases

-- Compare Working Directory to Staging Area
-- Shows changes between the working directory and the staging area.
git diff

-- Compare Staging Area to Last Commit
-- Shows changes between the staging area and the last commit
git diff --staged

-- Compare Working Directory to Last Commit
-- Shows changes between the working directory and the last commit
git diff HEAD

-- Compare Two Commits
-- Shows changes between two specific commits
git diff <commit1> <commit2>

-- Compare a Specific File
-- Shows changes in a specific file between the working directory and a commit, or between two commits.
git diff <commit> -- <file>

-- Compare Branches
-- Shows changes between two branches
git diff <branch1> <branch2>

Example Output

git diff
git diff <filename>
git diff --stat

git add

Description

It is used to add changes in the working directory to the staging area. This command prepares the changes to be included in the next commit.

Usage

git add [<options>] [--] <pathspec>...
  • <pathspec>: Specifies the files or directories to be added. This can be a specific file, a directory, or a pattern.

  • [--]: Used to separate paths from options, useful if the paths might be mistaken for options.

Options

-A or --all: Stages all changes (modifications, deletions, and untracked files).

-p or --patch: Interactively stage changes, allowing you to review each hunk before staging

-u or --update: Stages modifications and deletions, but not new untracked files.

-n or --dry-run: Shows what would be staged without actually staging the changes.

-v or --verbose: Shows the files as they are being added.

git add -A
git add -p
git add -u
git add -n
git add -v

What It Does

  1. Stages Changes: Adds changes in specified files or directories to the staging area.

  2. New and Modified Files: Tracks new files and stages changes in modified files.

  3. Does Not Affect Unchanged Files: Does not change the state of files that haven't been modified.

Staging Area: The staging area (also called the index) is an intermediate area where changes are listed to be included in the next commit. This allows to build up a commit incrementally, adding and reviewing changes before committing them.

Removing Files: To remove a file from the staging area, use:

git restore --staged filename.txt

Interactive Mode: Using git add -p is especially useful for selectively staging parts of files.

Common Use Cases

-- Add a Specific File
-- Stages changes in filename.txt for the next commit
git add filename.txt

-- Add All Changes
-- Stages all changes in the current directory and subdirectories
git add .

-- Add All Changes (Except Untracked Files)
-- Stages modifications and deletions, but not new untracked files
git add -u

-- Add All Changes in a Specific Directory
-- Stages all changes in the specified directory
git add path/to/directory

-- Add Changes Matching a Pattern
-- Stages changes in all .txt files
git add '*.txt'

-- Removing Files
-- To remove a file from the staging area
git restore --staged filename.txt

Example Output

When running git status after staging changes with git add

git rm

Description

It is used to remove files from the working directory and the staging area (index). This command stages the removal of files so that they will be deleted in the next commit.

Usage

git rm [<options>] [--] <file>...
  • <file>: Specifies the file(s) to be removed.

Options

-f or --force: Forces the removal of files. This is required if the files have been modified or if they are staged for commit.

-r or --recursive: Allows recursive removal of files in directories.

--cached: Removes the file only from the staging area, not from the working directory. This stops Git from tracking the file.

-n or --dry-run: Shows what would be removed without actually removing the files.

git rm -f filename.txt
git rm -r dirname/
git rm --cached filename.txt
git rm -n filename.txt

What It Does

  1. Removes Files from the Working Directory: Deletes the specified files from the working directory.

  2. Stages the Removal: Stages the deletion of the specified files, so the changes will be included in the next commit.

  3. Does Not Remove Directories: Only removes files, not directories.

Common Use Cases

-- Remove a Specific File
-- Removes filename.txt from both the working directory and the staging area
git rm filename.txt

-- Remove Multiple Files
-- Removes both file1.txt and file2.txt
git rm file1.txt file2.txt

-- Remove Files Using a Pattern
-- Removes all .log files from the working directory and stages the deletion
git rm '*.log'

-- Force Remove
-- Forces the removal of filename.txt even if it has been modified
git rm -f filename.txt

-- Keep File in Working Directory
-- Removes filename.txt from the staging area but leaves it in the working directory. 
-- This is useful for stopping tracking of a file without deleting it locally.
git rm --cached filename.txt

-- Untracked Files 
-- If we want to remove untracked files from the working directory, we can use the git clean command instead
git clean -f

Example Workflow

-- Check Current Status
git status

-- Remove a File
git rm filename.txt

-- Check Status Again
git status

-- Commit the Changes
git commit -m "Remove filename.txt"

Example Output

When running git status after using git rm

git commit

Description

It is used to record changes in the repository. It captures a snapshot of the project’s currently staged changes, making them part of the project’s history.

Usage

git commit [<options>] [--] [<file>...]
  • <file>: Optionally specify files to commit. If omitted, all staged changes will be committed.

Options

-m <msg> or --message=<msg>: Specifies the commit message directly in the command

-a or --all: Stages all tracked, modified files and commits them in one step

-v or --verbose: Shows the diff of changes in the editor during commit message writing.

--amend: Modifies the previous commit with new changes and/or a new commit message

--dry-run: Shows what would be committed without actually committing the changes.

-q or --quiet: Suppresses commit output

git commit -m "Add new feature"
git commit -a -m "Update all modified files"
git commit -v
git commit --amend -m "Correct previous commit message"
git commit --dry-run
git commit -q -m "Silent commit"

What It Does

  1. Creates a Commit: Saves the staged changes as a new commit in the repository.

  2. Includes a Commit Message: Each commit requires a message describing the changes.

  3. Associates Metadata: Each commit includes metadata like the author, date, and a unique hash identifier.

Commit Messages: Commit messages should be descriptive and concise, explaining the rationale for the changes. It's good practice to follow conventions such as the 50/72 rule: a short summary of 50 characters or less, followed by a blank line, and then a detailed description wrapped at 72 characters.

Atomic Commits: Each commit should represent a single logical change. This helps in understanding the project history and makes it easier to identify when specific changes were introduced.

Amending Commits: Be cautious with --amend if we've already pushed the original commit to a shared repository, as it rewrites history and can cause issues for others working with the same repository.

Revert Commits: If we have committed some changes and now wanted to undo the commit and bring back changes to staging or unstaging area then refer to git reset command.

Common Use Cases

-- Commit All Staged Changes
-- Commits all changes that have been staged with a message
git commit -m "Your commit message"

-- Commit Specific Files
-- Commits only the specified files
git commit <file1> <file2> -m "Commit message"

-- Interactive Commit
-- Opens the default text editor to enter a commit message
git commit

Example Workflow

-- 1. Stage Changes
git add .

-- 2. Commit All Staged Changes
git commit -m "Initial commit"

-- 3. Modify a File and Commit with Amend
echo "new content" >> file.txt
git add file.txt
git commit --amend -m "Add new content to file.txt"

-- 4. Commit All Tracked and Modified Files
git commit -a -m "Update modified files"

Example Output

When running git commit -m "Initial commit"

PreviousGetting and Creating ProjectsNextBranching and Merging

Last updated 8 months ago

Was this helpful?