└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # 100 Core Git Interview Questions in 2025
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | #### You can also find all 100 answers here 👉 [Devinterview.io - Git](https://devinterview.io/questions/web-and-mobile-development/git-interview-questions)
11 |
12 |
13 |
14 | ## 1. What is _Git_ and why is it used?
15 |
16 | **Git** is a decentralized version control system (**DVCS**) that developers primarily use to manage source code across diverse development projects. It ensures better code quality, facilitates teamwork, and provides a robust backup mechanism.
17 |
18 | ### Benefits of Using Git
19 |
20 | - **History and Time Travel**: Git preserves every version of a project, making it possible to roll back changes or inspect code at any point.
21 |
22 | - **Security and Integrity**: Each file in Git has a unique SHA-1 hash, which means unauthorized changes are easily detected.
23 |
24 | - **Collaboration**: Git allows multiple developers to work on a project simultaneously without conflict.
25 |
26 | - **Code Reviews**: Git simplifies the process of reviewing code before it's incorporated into the main codebase.
27 |
28 | ### Key Concepts
29 |
30 | #### Commit
31 |
32 | A **commit** represents a saved state of your project. It is a snapshot of all the files in your project at a given point in time. Each commit has a commit message associated with it.
33 |
34 | #### Branch
35 |
36 | A **branch** is an independent line of development. It allows you to work on a feature or bug fix, isolate it from the rest of the codebase until it is ready, and then merge it back in.
37 |
38 | **Master** is a default branch present in all Git repositories. You can create many other branches.
39 |
40 | #### Merge
41 |
42 | **Merging** in Git means taking the independent developments of two branches and combining them into a single branch.
43 |
44 | After merging, the two branches from which you were merging are the same as the merged branch.
45 |
46 | #### Remote and Origin
47 |
48 | A **remote** is a common repository on a server or accessible memory that all team members use to exchange their changes.
49 |
50 | An **origin** is a source of commit objects (store of all committed versions).
51 |
52 | ### The Command Line vs Visual Tools
53 |
54 | For everyday tasks, both CLI and GUI are powerful, but it's essential to understand **Git's** underlying mechanics so that you can troubleshoot and manage complex tasks efficiently.
55 |
56 | ### Beginner Tips
57 |
58 | - Make frequent commits.
59 | - Write clear and concise commit messages.
60 | - Push your code to a remote repository often, especially before taking a break or finishing a task.
61 |
62 |
63 | ## 2. How does _Git_ differ from other version control systems (_VCS_)?
64 |
65 | **Git** offers numerous advantages over traditional **Version Control Systems** (VCS), providing a distributed and efficient version control model.
66 |
67 | ### Unique Features
68 |
69 | - **Distributed Model**: Git decentralized nature empowers every set of files with a complete repository history and enables full-fledged operations without network connectivity. This stands in contrast to centralized systems that require a constant network connection and utilize a single centralized server for all project data.
70 |
71 | - **Quick Operations**: Git is renowned for its fast and efficient operations. Unlike older VCS, which often performed slowly or required substantial server interactions, Git uses local operations, resulting in impressive speed.
72 |
73 | - **Data Integrity**: Git ensures the cryptographic integrity of every piece of data, securing against file corruption, loss, or unauthorized alterations. The absence of this feature in some traditional VCS can pose data integrity risks.
74 |
75 | - **Streamlined Branching**: While segments or branches in older VCS were often used for parallel development, Git branches are lightweight and designed for quick and frequent usage.
76 |
77 | - **Customizable Workflows**: Git permits versatile workflows due to its distributed nature and the ability to manipulate the commit history before sharing changes with others.
78 |
79 | - **Staging Area (Index)**: Before committing, developers use the "staging area" to selectively include specific changes in a commit rather than committing every altered file.
80 |
81 | - **Powerful Library of Core Commands**: Git's robust set of indispensable commands enables a broad range of version control capabilities, from historical revision exploration to collaborative feature code management.
82 |
83 | ### Consider the User
84 |
85 | - **Simplicity and Flexibility**: Unlike some traditional VCS, Git is designed to be both user-friendly and capable of supporting complex tasks.
86 |
87 | - **Efficiency and Performance**: Git's rapid and streamlined processes lead to optimized efficiency.
88 |
89 | ### Unexpected Change? No Problem!
90 |
91 | - **Snapshot vs File Tracking**: Git's snapshots record the current state of the complete repository, whereas some traditional VCS, such as CVS and Subversion, primarily track file changes.
92 |
93 | - **Atomic Commits**: Every change is distinct and exclusive from others, enabling precise control over data synchronization.
94 |
95 | ### Git: Now and Hereafter
96 |
97 | - **Modern Landscape Readiness**: Git melodiously integrates with modern software development paradigms like Continuous Integration/Continuous Deployment (CI/CD).
98 |
99 | - **Cross-Platform Compatibility**: Be it Windows, macOS, or Linux, Git operates identically.
100 |
101 | #### What Are Some Drawbacks of Other VCS?
102 |
103 | - **Risk of Single Point of Failure**: If the central server is compromised, it poses a threat to the entire project's data.
104 |
105 | - **Version Numbering Limitations**: Users might be confined to a monotonically increasing number for versions, restricting granularity.
106 |
107 | - **Long-Term Integrity Risks**: Without cryptographic validation, files can be altered unnoticed.
108 |
109 | - **Data Loss Complications**: If a central server/repository is compromised or damaged, data loss is severe.
110 |
111 | - **Limited Offline Functionality**: Users are hindered by the necessity of a steady network connection.
112 |
113 | - **Stale Branches**: Centralized repositories can have stale branches, hindering collaboration.
114 |
115 |
116 | ## 3. What is the difference between _Git_ and _GitHub_?
117 |
118 | **Git** and **GitHub** are often confused due to their similar names. However, they serve different **version control** and development hosting purposes.
119 |
120 | ### Git
121 |
122 | **Git** is a **distributed version control system** that manages code and tracks its changes. It's mainly a local solution, only allowing developers to coordinate directly.
123 |
124 | #### Key Features
125 |
126 | - **Local Management**: Developers can work on their repositories without the need for a central server.
127 | - **Speed**: Operations such as committing, branching, and merging are rapid, ideal for local development.
128 | - **Staging Area**: Changes are first staged before getting committed for better control.
129 | - **Content Tracking**: Rather than file-based, Git is content-based, ensuring efficient tracking.
130 |
131 | ### GitHub
132 |
133 | **GitHub**, on the other hand, is a **web-based platform** that provides hosting for **Git repositories**. It offers features that extend beyond Git's core functionality.
134 |
135 | #### Key Features
136 |
137 | - **Remote Repositories**: It allows developers to sync their local repositories with remote ones, enabling collaborative work.
138 | - **Code Hosting**: Developers can store and manage their code from anywhere, not just their local machines.
139 | - **Collaboration Tools**: GitHub provides tools for project management, issue tracking, and team collaboration.
140 | - **Code Review**: Multiple users can review and discuss proposed changes before they're merged into the main codebase.
141 | - **Access Control**: Different users can have varying levels of access to a repository or organization.
142 |
143 |
144 | ## 4. What is a _repository_ in _Git_?
145 |
146 | A **Git repository** is a location where all the **version-controlled** files and their history are stored. It serves as the core component for collaborative and version control workflows.
147 |
148 | Every Git repository has two primary parts: the **working tree** and the hidden `.git` **directory**, where Git keeps all of its metadata for the repository.
149 |
150 | ### Key Features
151 |
152 | - **Distributed**: Each contributor to the project has their own copy of the repository, including its complete history and version-tracking capability. This enables offline work and serves as a backup for the project.
153 |
154 | - **Efficient Storage**: Git optimizes storage using techniques such as file hashing and delta compression, emphasizing minimal redundancy and data redundancy elimination.
155 |
156 | - **Content Integrity**: All files in a Git repository, as well as their versions, are checksummed and verified on every Git operation for data integrity.
157 |
158 | - **Work Tracking**: Git allows for tracking changes made to the project over time, helping individuals or teams understand the evolution of the project, who made specific changes, and why.
159 |
160 | ### .git Directory
161 |
162 | The `.git` directory is the **control center** of a Git repository, housing everything Git needs to manage the repository and its history. It includes:
163 |
164 | - The **object database** that hosts all the data about commits, trees, and blobs.
165 | - The **references** directory maintaining pointers to specific commits (e.g., branches and tags).
166 | - Configuration files detailing the repository's settings and attributes.
167 |
168 | ### Working Tree
169 |
170 | The working tree is a directory where **tracked files** are extracted for **viewing** and **editing**. Any changes made to files in the working tree can be staged and committed to the repository to capture the changes.
171 |
172 | Untracked files, i.e., files not previously staged or committed, coexist with the working tree and reside outside the Git management.
173 |
174 | ### Code Example: Working Tree
175 |
176 | Here is the Python code:
177 |
178 | ```python
179 | # Let's define a variable to point to the .git directory
180 | git_directory = '.git'
181 |
182 | # Now, we can simulate the construction of our working tree using a dictionary
183 | working_tree = {
184 | 'folder1': {
185 | 'file1.py': 'print("Hello, World!")'
186 | },
187 | 'folder2': {
188 | 'file2.py': 'print(2 + 2)'
189 | }
190 | }
191 | ```
192 |
193 |
194 | ## 5. Explain the concept of a _commit_ in _Git_.
195 |
196 | In **Git**, a **commit** represents a snapshot of a project at a specific point in time. Each commit records the changes made, the author, and a unique identifier.
197 | It is organized in a **directed acyclic graph** (DAG), which aligns with its branching model.
198 |
199 | ### Key Elements of a Git Commit
200 |
201 | - **Tree**: Represents the state of the project's file system at the time of the commit. The tree object is a record of the location and content of each file in the repository.
202 | - **Parent Commit(s)**: Identifies the commit(s) from which the current commit originated. In the case of the initial commit, there's no parent.
203 | - **Metadata**: Includes details such as the commit's author, date, and a message summarizing the changes made.
204 |
205 | ### The Three-Tree Architecture
206 |
207 | In a typical Git repository, there is a **working directory**, **staging area**, and **commit history**. Each tracks the project's state at various stages.
208 |
209 | - **Working Directory**: Refers to the current, live set of files and directories. This is the version of the project that you actively work on and modify.
210 | - **Staging Area** (also known as the "index"): Serves as a buffer zone. Files in this area are marked for inclusion in the next commit. You control what content moves from the working directory to the staging area.
211 | - **Commit History** (in the Git directory): Represents the timeline of commits in the form of a versioned archive. It also houses the full content of the project at relevant commit points.
212 |
213 | ### The Git Lifecycle
214 |
215 | The standard git-flow follows a lifecycle that incorporates the three trees mentioned above.
216 |
217 | - **Creating Commits**: You start by making changes to your working directory. When you're ready to record these changes, you add specific files from the working directory to the staging area. With the desired changes in the staging area, the next command captures the staging area's content and creates a new commit in the commit history.
218 |
219 | - **Browsing History**: Git's commit history is time-ordered, typically from the most recent commit backward. Each commit influences how the project appears at a given point in time.
220 |
221 | ### Viewing Commit History
222 |
223 | You can view the commit history using commands such as `git log`. This command provides a structured list of commits, detailing the author, commit date, and an associated commit message.
224 |
225 | ### Practical Applications
226 |
227 | - **Code Reversion**: You can reset a project to an earlier commit, effectively reversing changes.
228 | - **Collaboration**: Commits facilitate collaboration by enabling team members to understand changes and when they were made.
229 | - **Code Review**: Before incorporating changes into the primary branch, commits offer a structured way for team members to review each other's code. This process ensures that new code meets the repository's standards.
230 |
231 | ### Code Example: Commit Creation and Viewing
232 |
233 | Here is the Git console command to create "Meaingful Commit" with a message and then to view the Commit.
234 |
235 | ```bash
236 | # To make a commit with a message
237 | git commit -m "Meaningful Commit"
238 |
239 | # To view the commit history
240 | git log
241 | ```
242 |
243 |
244 | ## 6. What is the difference between a _working directory_, _staging area_, and _repository_ in _Git_?
245 |
246 | **Git** is characterized by a three-tiered architecture which includes the following layers:
247 |
248 | - **Working Directory**
249 | - **Staging Area**
250 | - **Repository**
251 |
252 | Each layer plays a distinct role in the Git architecture.
253 |
254 | ### Core Concepts
255 |
256 | #### Working Directory
257 |
258 | The working directory is your playground. It's your space for experimenting, where you can **edit files**, merge different versions, and even create new ones.
259 |
260 | #### Staging Area (Index)
261 |
262 | The staging area (also known as the Index) is a kind of **middle-ground**. Here you can make fine adjustments to what changes will be included in your next commit. You have two types of files here:
263 |
264 | - **MDS**: Files that have been modified since your last commit
265 | - **SML**: Files that have been changed and prepared for your next commit
266 |
267 | When you're happy with your changes in the staging area, you "stage" them. Staging in this context is like flagging certain parts of your project that you want to be saved in your next commit. Notice that this step is completely **optional.**
268 |
269 | #### Repository (History)
270 |
271 | The repository is the final tier, dealing with the preservation of your work. Think of it as the **local repository** that serves as the safe house for all your commits. It keeps track of all changes and commits you've made, ensuring that you can still retrieve them even after major updates.
272 |
273 | The repository is also broken down into three apparent "trees" - the Working Directory, the Staging Area, and the last one, the HEAD. The HEAD points to your most recent commit. These three trees can seem confusing at first. But really, they're straightforward to understand - they represent the current status of your project, changes that you're planning to commit, and the commits that you've confirmed you want to save in the future.
274 |
275 |
276 | ## 7. Define _branching_ in _Git_ and its importance.
277 |
278 | **Branching** in **Git** allows for the independent development of distinct features or sections of the codebase. It's a crucial version control strategy, particularly in collaborative projects.
279 |
280 | ### Key Concepts
281 |
282 | - **Master/Trunk/Branch**: The primary branch serving as the project source.
283 |
284 | - **Feature Branches**: Additional branches dedicated to specific features or tasks, often derived from the Master branch.
285 |
286 | - **Merging**: The process of integrating changes from one branch into another. For instance, integrating finished feature branches into the Master.
287 |
288 | - **Conflict Resolution**: The act of resolving overlapping changes made to the codebase across different branches.
289 |
290 | ### The Importance of Branching
291 |
292 | 1. **Code Isolation**: Each feature branch is an isolated environment for developing a specific feature. This avoids interference with the main codebase.
293 |
294 | 2. **Collaborative Development**: Allows multiple developers to work on the same codebase concurrently, minimizing conflicts.
295 |
296 | 3. **Risk Mitigation**: Changes are kept separate until they are thoroughly tested. If an experimental feature doesn't work as expected or introduces bugs, it won't affect the more stable Master branch.
297 |
298 | 4. **Staging Area**: A dedicated space for integration and testing before code is deployed or merged into the Master branch.
299 |
300 | 5. **Feature Toggles**: Streamlines the process of selectively deploying new features for testing.
301 |
302 | 6. **Code Reviews**: Assists in code quality checks before merging, ensuring the Master branch remains stable.
303 |
304 | 7. **Task Management**: Aligns with project management tools and methodologies, providing a way to structure tasks in a version-controllable manner.
305 |
306 | 8. **Release Management**: Facilitates the isolation and verification of changes earmarked for specific releases.
307 |
308 |
309 | ## 8. What is a `HEAD` in _Git_?
310 |
311 | In **Git**, the concept of a **working directory**, the **staging area** (or **index**), and the **repository** (or **commit history**) are all managed by the `HEAD`.
312 |
313 | ### Role of `HEAD` in Git
314 |
315 | - **Point of Reference**: `HEAD` identifies the current snapshot/commit in the history tree. Any actions in the working directory or staging area are based on this commit.
316 |
317 | - **Connector between Levels**: It links the most recent commit in a branch to both the staging area and the working directory. Each commit is precisely what `HEAD` points to.
318 |
319 | ### Code Example: Working with `HEAD`
320 |
321 | Here is the visual representation of **How Git Works**.
322 |
323 | Here is the `python` code:
324 |
325 | ```python
326 | # Check out the "first-branch" branch
327 | git checkout first-branch
328 |
329 | # Make some modifications and stage them
330 | git add modified-file-1.txt
331 |
332 | # Commit the staged changes
333 | git commit -m "Modified file 1 in first branch"
334 |
335 | # Verify the new `HEAD` after the commit
336 | git log --oneline --decorate
337 | ```
338 |
339 | The **`git log`** command in the above code includes the `--decorate` option, displaying the most recent commit and any associated references.
340 |
341 |
342 | ## 9. What does the 'clone' operation in _Git_ do?
343 |
344 | **Cloning** in **Git** creates a **local copy** of the repository, allowing for version control and collaborative work. It establishes a link to a specified remote, permitting **fetch** and **push** operations.
345 |
346 | ### Key Attributes
347 |
348 | - **Two-Part Process**: Cloning involves duplicating the repository and setting up the local environment.
349 | - **Full Version History**: The cloned repository typically includes all commits and file versions.
350 | - **Remote Linkage**: A relationship is built with a designated remote for data synchronization.
351 |
352 | ### Terminology Overview
353 |
354 | - **Local Repository**: Storage on the user's machine where all project and version data reside.
355 | - **Remote Repository**: An external, shared storage often on a server, accessible for collaborative work.
356 | - **Working Directory**: The location on the user's file system where files are manipulated and changes are tracked for commits.
357 |
358 | ### Core Functionality
359 |
360 | - **Duplication**: The clone process reproduces the entire project, with all branches and commits, onto the user's machine. This offers a complete, standalone history.
361 | - **Configuration**: The local environment is configured to maintain synchronization with a specific remote repository. By default, the repository from which the clone is made (origin) is set as the primary remote, but additional remotes can be added if required.
362 | - **Integrity**: Git ensures the integrity of the copied data, such as commits and file snapshots, during the cloning process.
363 | - **Selective History Contraints**: While it's common for a clone to receive the entire repository history, limited cloning is also possible, especially with large repositories. Technique like shallow cloning or specifying a certain commit for cloning can be used.
364 |
365 | ### Forming the Connection
366 |
367 | After a successful clone, the local repository is configured to interact with a designated remote repository, typically on a centralized server like Github or Bitbucket.
368 |
369 | For GitHub, cloning often uses the HTTPS mode. Upon updates to the remote, the local repository can be synchronized using standard Git commands (e.g., **fetch**, **pull**, **push**).
370 |
371 | Technically, clonality is not tied to a specific remote URL; it's more about aligning the histories. For instance, after cloning from GitHub using HTTPS, remotes can be reconfigured to use SSH.
372 |
373 | ### Detailed Process
374 |
375 | 1. **Acquiring Data**: The clone command contacts the remote repository, retrieves its history and files, and then saves this snapshot locally.
376 |
377 | 2. **Repository Creation**: The `git clone` execution sets up a new repository, employing the data fetched from the target remote, and thus creates both the working directory and associated `.git` directory, which hosts the entire Git control structure.
378 |
379 | 3. **Linkage Configuration**: The clone operation automatically establishes a remote connection, naming it "**origin**" by default. Should you have multiple remotes or wish to use a different name, configuration adjustments may be required.
380 |
381 | 4. **Extraction**: The clone accomplishes the creation and association of the local repository, which users can then "extract" to their working directories for manipulation.
382 |
383 | 5. **Status Verification**: Confirming the successful execution of a clone can be done by taking a look at the current remotes via `git remote -v`, which should display the origin.
384 |
385 | ### Technical Commands
386 |
387 | - **Clone**: Initiate the cloning process.
388 | ```bash
389 | git clone
390 | ```
391 |
392 | - **Remote**: Verify origin setup.
393 | ```bash
394 | git remote -v
395 | ```
396 |
397 |
398 | ## 10. How does _Git_ store information?
399 |
400 | While **Git** does use a filesystem to store data, it isn't exclusively file-based. The three main components of the **Git** data structure are the **repository**, the **index/staging area**, and the **local working copy**.
401 |
402 | ### Git Storage Model
403 |
404 | 1. **Local Working Copy**: Where you directly interact with your files.
405 | 2. **Staging Area (Index)**: Serves as a sort of "holding area" for changes you want to include in your next commit.
406 | 3. **Local Repository**: Where **Git** keeps track of the complete history and stores different versions of your files.
407 |
408 | ### Repository
409 |
410 | The **repository** houses the following key components:
411 |
412 | - **Object Database**: Persistently stores snapshots of files and directories as objects, which can be further classified into:
413 |
414 | - **Blob** objects for individual file contents.
415 | - **Tree** objects that replicate file system hierarchy.
416 | - **Commit** objects linked to a specific state in the project's history.
417 | - **Tag** objects marking specific commits, often used for releases.
418 |
419 | - **Index/Stage**: A dynamic workspace that mirrors the next commit's expected state.
420 |
421 | - **Head Pointer**: A reference to the latest commit in your current working branch
422 |
423 | - **Branches**: Human-readable names that reference specific commits, facilitating independent lines of development.
424 |
425 | ### Git Object Names
426 |
427 | 1. **Blobs**: SHA-1 hash is based on the file's content.
428 | 2. **Trees**: SHA-1 hash combines the file and directory contents within—changes in any file or sub-directory would trigger a new hash.
429 | 3. **Commits**: SHA-1 hash incorporates the tree representing the project's directory structure, along with parent commit(s), commit message, and author information.
430 |
431 | ### Git Object Storage
432 |
433 | Git allows for a 'lazy write' mechanism for objects. This means that an object file is written upon creation and remains unchanged until the content it represents changes. When a change occurs, it gets updated and its SHA-1 is recalculated. This particular feature is known as 'immutable storage'.
434 |
435 | Here's an illustration for better understanding:
436 | - Let's assume a file's content changes and you add the updated file to the staging area.
437 | - The new version of the file is then stored as a **Blob** object, and the associated **Tree** object also gets updated.
438 | - During the following commit, a new **Commit** object is created, which references the updated **Tree** object.
439 | - Simultaneously, the **Branch** you're working on moves forward to reference this new commit.
440 |
441 | This systematic approach assures the integrity of your project's history. Since any alteration in content, directory structure, or commit details will trigger a change in the SHA-1 hash of the related object(s), a change can be immediately recognized.
442 |
443 |
444 | ## 11. How do you initialize a new _Git_ repository?
445 |
446 | Let's go through the step-by-step process of **creating a new Git repository** and then getting started by **adding files**, **making commits**, and **pushing** the repository to a remote location such as GitHub or Bitbucket.
447 |
448 | ### Initializing a New Git Repository
449 |
450 | #### Using the Command Line
451 |
452 | 1. Navigate to your project folder using your terminal or command prompt.
453 | 2. Run the following command to initialize a new Git repository:
454 |
455 | ```bash
456 | git init
457 | ```
458 |
459 | #### Using Git GUI
460 |
461 | Most Git GUI applications, like Sourcetree or GitKraken, facilitate setting up repositories through an intuitive interface. Once you've navigated to your project folder, choose the "Initialize/Create New Repository" option.
462 |
463 | ### Getting Started: Adding Files, Making Commits, and Pushing to Remote
464 |
465 | #### Adding Files to the Staging Area
466 |
467 | Use the following command to **add** files or directories to the staging area:
468 |
469 | ```bash
470 | # To add a specific file
471 | git add filename
472 |
473 | # To add all files and directories
474 | git add .
475 | ```
476 |
477 | #### Committing Changes
478 |
479 | Once files are in the staging area, use this command to **commit** these changes:
480 |
481 | ```bash
482 | git commit -m "Your commit message goes here"
483 | ```
484 |
485 | #### Associating a Remote Repository
486 |
487 | If you plan to push your local repository to an online service like GitHub, first **link** your local repository to a remote one:
488 |
489 | ```bash
490 | git remote add origin your-remote-repository-url
491 | ```
492 |
493 | Replace "your-remote-repository-url" with the URL provided by your online repository.
494 |
495 | #### Pushing to Remote
496 |
497 | Finally, use this command to **push** your local repository to the remote one:
498 |
499 | ```bash
500 | git push -u origin master
501 | ```
502 |
503 | After the initial "upstream" link is established, subsequent push commands can be executed with a simple `git push`.
504 |
505 | ### Handling Sensitive Information
506 |
507 | To ensure that sensitive data, such as API keys or credentials, are not shared, employ the **`.gitignore`** file to list files and patterns that should be excluded from version control.
508 |
509 | In particular, avoid using files with such sensitive information before creating a `.gitignore`.
510 |
511 | Here is the `.gitignore` file:
512 |
513 | ```plaintext
514 | # Ignored file - example
515 | credentials.txt
516 | ```
517 |
518 |
519 | ## 12. Explain the purpose of the `git status` command.
520 |
521 | **`git status`** is an essential command for **tracking changes** in a Git repository. It provides important details such as file states, current working branch, untracked files, and more.
522 |
523 | ### Key Output Information
524 |
525 | - **On Branch:** Indicates the active branch, allowing quick navigation through different branches.
526 |
527 | - **Changes to be Committed:** Lists modified or staged files, providing a quick glance at what will be included in the next commit.
528 |
529 | - **Changes not staged for commit:** Highlights modified files that were not yet staged for the next commit.
530 |
531 | - **Untracked Files:** Recognizes files in the working directory that are not a part of the repository.
532 |
533 | - **Branch is Up to Date:** Provides this affirmation when the working branch is up-to-date with its remote counterpart.
534 |
535 | - **Your Branch is Ahead of 'origin/master' by 1 Commit:** Notifies when the current local branch outpaces the linked remote branch by a set number of commits. This is common in team-based workflows and signifies the necessity of a `push`.
536 |
537 | **Note**: The remote branch in the example is 'origin/master', and the number of commits ahead is 1.
538 |
539 | ### Code Example: Terminal Output of `git status`
540 |
541 | Here is the code:
542 |
543 | ```shell
544 | On branch main
545 | Your branch is up to date with 'origin/main'.
546 |
547 | Changes to be committed:
548 | (use "git restore --staged ..." to unstage)
549 | modified: app.js
550 |
551 | Untracked files:
552 | (use "git add ..." to include in what will be committed)
553 | server.js
554 |
555 | no changes added to commit (use "git add" and/or "git commit -a")
556 | ```
557 |
558 | ### Code Example: Visual Diff of Staged Changes using `git diff --staged`
559 |
560 | Here is the code:
561 |
562 | ```shell
563 | diff --git a/readme.txt b/readme.txt
564 | index ce01362..0602794 100644
565 | --- a/readme.txt
566 | +++ b/readme.txt
567 | @@ -1 +1 @@
568 | - Initial file version
569 | + Modified during stage
570 | ```
571 |
572 | ### Code Example: Multifile `git status` Output
573 |
574 | Here is the code:
575 |
576 | ```shell
577 | On branch: master
578 | Changes to be committed:
579 | (use "git reset HEAD ..." to unstage)
580 | modified: file1.cpp
581 | modified: file2.cpp
582 | Both file3.cpp and file4.cpp are untracked.
583 | Your branch and 'origin/master' have diverged,
584 | and have 4 and 2 different commits each, respectively.
585 | ```
586 |
587 | ### Best Practices
588 |
589 | - Regularly use `git status` to stay updated on the repository's state.
590 | - Review and comprehend the provided information before proceeding with any actions, such as staging or committing.
591 |
592 |
593 | ## 13. What does the `git add` command do?
594 |
595 | **`git add`** is the first step in tracking changes you make to existing files or adding new files to your Git repository. It prepares the changes for the next commit by moving modified or new files to the **staging area**.
596 |
597 | When you invoke `git add`, three major actions take place:
598 |
599 | 1. **File Selection**: You choose which **specific file changes** to include in the upcoming commit.
600 |
601 | 2. **File Comparison**: Git analyzes the selected files and identifies the exact line-by-line or block-level modifications.
602 |
603 | 3. **Staging Area Update**: The selected file changes are prepared and categorized. Once you're ready, you can make a commit action to move all the changes in the staging area to the repository.
604 |
605 | ### Relation Manager
606 |
607 | The staging area acts as a bridge between your working directory and the repository (history).
608 |
609 | - **Working Directory**: Contains the active files you're currently editing.
610 |
611 | - **Staging Area (Index)**: A kind of "Sandbox" where you selectively group changes together for precise commits.
612 |
613 | - **Repository**: The historical record of all your commits and their respective states.
614 |
615 | ### Key Actions
616 |
617 | - **Add All Modifications**: Restage modified files to the current state: `git add .`
618 |
619 | - **Add Interactively**: Handpick changes from modified files: `git add -p`
620 |
621 | - **Merge Conflicts**: After addressing conflicts, ready files for commit: `git add `
622 |
623 | ### Code Example: Staging vs Git History
624 |
625 | Here is the Python code:
626 |
627 | ```python
628 | # File: my_file.py (in the working directory)
629 |
630 | # Current content
631 | print("This line is part of the initial version.")
632 |
633 | # Post staging changes (not committed yet)
634 | print("This line will be part of the next commit.")
635 | ```
636 |
637 | In our Python example, consider "file.py" as the file. Initially, the file contains one line, which was the initial version. Then "This line will be part of the next commit." gets added (not committed yet), so that these changes occur between `git add` and `git commit`.
638 |
639 |
640 | ## 14. How do you create a _commit_ in _Git_?
641 |
642 | Let's look at the process of **creating a commit in Git**:
643 |
644 | ### 1. Identifying Tracked and Untracked Files
645 |
646 | Before making a commit, the user should review any changes in the working directory and staging area.
647 |
648 | **Untracked Files**: These are new files that Git does not track yet. To track untracked files and subsequently include them in a commit, they need to be staged using the `git add` command.
649 |
650 | **Tracked Files**: Files that have previously been committed or added to the staging area can be included in the next commit.
651 |
652 | ### 2. Ways to Select Files for Commit
653 |
654 | #### `git add` Options
655 |
656 | - **Specific Files**: Directly add individual files or a group of files using their names or paths.
657 |
658 | ```bash
659 | git add file1.txt path/to/file2.txt
660 | ```
661 |
662 | - **By Pattern**: Use wildcards or named sets of files to add multiple files at once.
663 |
664 | ```bash
665 | git add *.txt
666 | ```
667 |
668 | - **Interactively**: Launch a prompt where changes can be reviewed and selected for staging.
669 |
670 | ```bash
671 | git add -i
672 | ```
673 |
674 | #### `git rm` and `git mv`
675 |
676 | These commands remove and rename files respectively. Changes are then staged and committed similarly to new additions.
677 |
678 | #### `git reset`
679 |
680 | Unstage files that were mistakenly added to the staging area.
681 |
682 | ```bash
683 | git reset file1.txt
684 | ```
685 |
686 | #### `git checkout`
687 |
688 | To remove changes in the working directory, bring them back to the state of the `HEAD` commit.
689 |
690 | ```bash
691 | git checkout file1.txt
692 | ```
693 |
694 | #### `git commit`
695 |
696 | This command is used to save changes to the local repository after they have been staged.
697 |
698 | Parameters (optional):
699 |
700 | ##### `-m`
701 | Use a one-line message to describe the commit.
702 |
703 | ```bash
704 | git commit -m "Add new feature xyz"
705 | ```
706 |
707 | ##### `-a`
708 | Stage all modified files and commit them.
709 |
710 | This command omits the staging step, effectively combining `git add` and `git commit`. Since it bypasses the staging area completely, care should be taken when using it, to ensure only intended changes are included in the commit.
711 |
712 | ```bash
713 | git commit -am "Update feature xyz"
714 | ```
715 |
716 | When using `-a` without `-m`, Git will open the default text editor for you to compose the commit message in a separate file.
717 |
718 | ### 4. Excluding Files from a Commit
719 |
720 | Some files might not need to be committed, for example:
721 |
722 | - **Temporary Files**: This might include build artifacts or editor-specific temporary files.
723 | - **Sensitive Information**: Such as passwords or private keys.
724 |
725 | For such exclusions, you can define the file patterns or names in a `.gitignore` file.
726 |
727 | To exclude files globally, create or edit the global `.gitignore` file.
728 |
729 | ```bash
730 | git config --global core.excludesfile ~/.gitignore_global
731 | ```
732 |
733 | Then, ensure to add a `.gitignore` file in the root directory for the local repository if needed.
734 |
735 | ```bash
736 | touch .gitignore
737 | ```
738 |
739 | ### CAUTION:
740 |
741 | - Avoid tracking, staging, or committing sensitive information.
742 | - Keep `.gitignore` up to date, especially in collaborative projects.
743 |
744 |
745 | ## 15. What information is contained in a _commit object_ in _Git_?
746 |
747 | The **commit object** in Git encapsulates rich textual data that aids in tracking and managing changes in the repository.
748 |
749 | ### Core Elements in a Commit Object
750 |
751 | - **Author and Committer**: These metadata entries contain the individual's name and **email** address as well as the timestamp.
752 | - **Commit Messages**: They provide a brief yet comprehensive understanding of the changes introduced in the commit, helping in maintaining clarity and context.
753 | - **Parent Commits**: This represents a pointer to one or more parent commits. In the case of a merge commit, there can be more than one parent.
754 | - The `HEAD` of most branches points to the most recent commit, and this `reference` is what progresses as newer commits occur. The `HEAD` itself points to the most recent commit but operates **indirectly** through the branch reference.
755 |
756 | ### Other Core Contents
757 |
758 | - **Tree Object**: Each commit is linked to a **tree object** that represents the state of the content in the repository at the time of the commit. The tree object, in turn, holds references to the various blobs and subtrees.
759 | - Here is a quick summary. A blob in Git is a file, and a tree is a collection of files and can even include other trees.
760 | - A commit, therefore, is created with a tree-referencing object, capturing both the checked-in version of files (through the tree object) and a metadata snapshot (through its unique SHA key).
761 | - Internal to that tree are also the various subtrees and blobs that the tree sticks to.
762 |
763 | ### Dangling Commits
764 |
765 | In cases when a branch or reference no longer points to a commit, Git still retains these **dangling commits**. Using `git reflog`, you can potentially recover them.
766 |
767 | ### Verification with GPG
768 |
769 | Advanced Git workflows often call for data integrity and authenticity, especially in distributed teams and open-source projects. Git employs GitPG to sign commits, verifying the commit objects' authenticity, flagging potential tampering or forging of prior commits.
770 |
771 |
772 |
773 |
774 | #### Explore all 100 answers here 👉 [Devinterview.io - Git](https://devinterview.io/questions/web-and-mobile-development/git-interview-questions)
775 |
776 |
777 |
778 |
779 |
780 |
781 |
782 |
783 |
--------------------------------------------------------------------------------