Setting Up Git
Most modern operating systems include Git by default. Verify your installation by running git --version in your terminal. If it is missing, download the binary from the official Git website.
Configure your identity before performing your first commit, as Git embeds this metadata into your project history:
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
You can inspect these settings at any time by viewing ~/.gitconfig.
Local Repository Management
To begin version control in a directory, initialize the anvironment:
git init
This command creates a hidden .git folder, which tracks your project's evolution. To exclude specific files (like build artifacts or dependency folders) from tracking, create a .gitignore file and list the paths to ignore, such as:
# Ignore cache directory
__pycache__/
Versioning Workflow
- Check Status: Use
git statusto identify modified or untracked files. - Stage Changes: Prepare files for commit using
git add <filename>orgit add .for all changes. - Commit: Save your changes to the project history:
git commit -m "Descriptive summary of changes" - Log History: Review past commits with
git logorgit log --onelinefor a concise overview.
Reverting and Branching
To discard uncommitted changes in your working directory, use git restore .. For more complex operations, such as resetting the state of your project to a previous commit, utilize git reset --hard <commit-hash>.
Branches allow you to work in isolation. Create and switch to a new branch with git checkout -b <branch-name>. Switch back to the primary branch using git checkout main.
Collaborative Development with GitHub
GitHub acts as a centralized remote host for your Git repositories.
SSH Authentication
To authenticate securely, generate an SSH key pair:
ssh-keygen -t rsa -b 4096 -C "you@example.com"
Add the contents of your public key (~/.ssh/id_rsa.pub) to your GitHub account settings under the "SSH Keys" section. Test the connection with ssh -T git@github.com.
Remote Repository Synchronization
If you have an existing local repository, link it to GitHub:
git remote add origin git@github.com:username/repository.git
git push -u origin main
Alternatively, for new projects, start by cloning the remote repository directly:
git clone git@github.com:username/repository.git
To synchronize changes, use git pull to fetch and merge remote updates, and git push to upload your local commits.
Advanced Operations
- Rebasing:
git rebase mainallows you to move your current branch's base to the latest commit of the main branch, creating a cleaner, linear history. - Submodules: Integrate external repositories as sub-dependencies using
git submodule add <url>. - Handling Unrelated Histories: When merging two separate projects, append the
--allow-unrelated-historiesflag togit pullto override the default safety check.