Staging changes in Git is the process of preparing files to be included in the next commit. This allows you to selectively choose which changes to commit, providing granular control over your version history. Below are the steps to stage changes for a commit, along with sample commands and explanations.

Staging Changes Using git add

The git add command is used to stage changes. You can stage individual files, multiple files, or all changes in the working directory.

Staging a Single File

To stage a single file, use the git add command followed by the file name.

    
# Stage a single file
git add file.txt

# Verify the staged changes
git status

# Output example:
# On branch main
# Changes to be committed:
# (use "git restore --staged <file>..." to unstage)
# modified: file.txt

Staging Multiple Files

To stage multiple files, list them all after the git add command.

    
# Stage multiple files
git add file1.txt file2.txt

# Verify the staged changes
git status

# Output example:
# On branch main
# Changes to be committed:
# (use "git restore --staged <file>..." to unstage)
# modified: file1.txt
# modified: file2.txt

Staging All Changes

To stage all changes in the working directory, use the git add . command.

    
# Stage all changes
git add .

# Verify the staged changes
git status

# Output example:
# On branch main
# Changes to be committed:
# (use "git restore --staged <file>..." to unstage)
# modified: file1.txt
# modified: file2.txt
# new file: file3.txt

Unstaging Changes

If you accidentally stage a file and want to unstage it, use the git restore --staged command.

    
# Unstage a file
git restore --staged file.txt

# Verify the unstaged changes
git status

# Output example:
# On branch main
# 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: file.txt
#
# no changes added to commit (use "git add" and/or "git commit -a")

Committing Staged Changes

Once you have staged your changes, you can commit them using the git commit command.

    
# Commit the staged changes
git commit -m "Added new features and fixed bugs"

# Output example:
# [main abc123] Added new features and fixed bugs
# 3 files changed, 10 insertions(+), 2 deletions(-)

Conclusion

Staging changes for a commit is a crucial step in the Git workflow. By using the git add command, you can selectively choose which changes to include in your next commit. This provides granular control over your version history and ensures that only the desired changes are recorded. Understanding how to stage and unstage changes is essential for effective version control and collaboration in Git.