2025-02-23 Programming, Productivity
Understanding the Git Workflow
By O. Wolfson
Git operates through three main areas:
- Working Directory: This is where you modify files in your project. Any changes made here are considered unstaged.
- Staging Area (Index): Files added to this area are prepared for the next commit. This allows you to control which changes are included.
- Repository: The committed changes are stored here as a permanent part of the project's history. This can be local or remote (on GitHub, GitLab, etc.).
The workflow generally follows this sequence:
- Modify files in the working directory.
- Add specific files to the staging area (
git add
). - Commit the staged changes to the repository (
git commit
). - Push commits to a remote repository for backup or collaboration (
git push
).
Creating a New Repository (git init
)
To start tracking files with Git, initialize a new repository:
shmkdir my_project
cd my_project
git init
This creates a hidden .git
directory that holds all version control information.
Tracking Files & Making Commits
After initializing a repository, Git does not automatically track files. You must explicitly add them:
shecho "# My Project" > README.md
Check the status of the repository:
shgit status
Stage the file:
shgit add README.md
Commit the changes with a meaningful message:
shgit commit -m "Initial commit: Added README"
Viewing Changes (git status
, git diff
)
git status
shows which files are modified, staged, or untracked.git diff
displays differences between the working directory and the staging area.git diff --staged
compares the staging area with the last commit.
Understanding Commit History (git log
, git show
)
git log
displays the commit history in reverse chronological order.git log --oneline
gives a concise summary of commits.git show <commit_hash>
provides details of a specific commit.
Example:
shgit log --oneline
Output:
text4f6b3c2 Initial commit: Added README
To view details of a commit:
shgit show 4f6b3c2
Hands-on Exercise: Create a New Repo, Track Changes, and Commit with Meaningful Messages
- Initialize a new Git repository:
sh
mkdir my_git_project cd my_git_project git init
- Create a new file and check Git status:
sh
echo "Hello, Git!" > hello.txt git status
- Stage and commit the file:
sh
git add hello.txt git commit -m "Added hello.txt with a greeting message"
- Modify the file and view changes:
sh
echo "Welcome to version control." >> hello.txt git diff
- Stage and commit the changes:
sh
git add hello.txt git commit -m "Updated hello.txt with an additional message"
- View commit history:
sh
git log --oneline
This exercise helps solidify the Git workflow and best practices for managing source code effectively.