10 Essential Git Commands Every Developer Should Know

admin
admin

1. git init – Initialize a New Repository

Every Git journey begins with git init. This command creates a new .git subdirectory in your project folder, transforming an ordinary directory into a Git repository. It establishes the foundational data structures—objects, refs, and HEAD pointer—that Git uses to track changes. Use it once per project: git init in your project root. For existing projects, git init can be run safely; it won’t overwrite existing files. Advanced usage includes git init --bare for creating a server-side repository without a working tree, essential for team collaboration. Always verify with ls -la .git to confirm initialization. Because Git is decentralized, git init is the first step to local version control before connecting to remotes.

2. git clone – Copy a Remote Repository Locally

git clone downloads an entire repository from a remote source (GitHub, GitLab, Bitbucket) to your local machine. The syntax is git clone [directory-name]. It automatically configures the remote as origin and sets up tracking branches. Use --depth 1 for a shallow clone when you only need the latest commit—ideal for large repositories or CI/CD pipelines. To clone a specific branch, add --branch . The command also copies all remote-tracking branches, tags, and commit history. Avoid cloning into an existing directory; Git will refuse. For SSH-based cloning (preferred for security), ensure your SSH key is added to the agent. git clone is the standard doorway to contribute to open-source projects or onboard into a team’s codebase.

3. git add – Stage Changes for Commit

The git add command moves modified or new files into the staging area (index), preparing them for the next commit. Without it, Git ignores uncommitted work. Use git add for specific files, git add . for all changes in the current directory (including deletions), or git add -A for the entire working tree. For fine-grained control, git add -p launches interactive hunk staging—review each change chunk-by-chunk and decide whether to stage it. This is critical for crafting clean, focused commits. Undo staging with git reset HEAD . Never use git add . carelessly; it can accidentally include generated files, debug logs, or sensitive credentials unless you have a .gitignore file. Always run git status before and after staging to verify.

4. git commit – Record Changes to the Repository

git commit creates a snapshot of the staged changes, permanently storing them in the repository’s history. The fundamental form is git commit -m "Your descriptive message". Write messages in the imperative mood: “Fix login bug” not “Fixed login bug.” A well-crafted commit message includes a short summary line (≤50 characters) followed by a blank line and a detailed body (72 characters per line) explaining what and why. Use git commit -a to skip staging and commit all tracked file changes (use with caution—this bypasses selective staging). For corrections, git commit --amend modifies the last commit’s message or adds new changes (only if not pushed). Atomic commits (one logical change per commit) improve bisectability and code review. Run git log afterward to confirm your commit appears in history.

5. git branch – Manage Branches

Branches in Git are lightweight pointers to specific commits, enabling parallel development. git branch lists all local branches; an asterisk marks the current branch. Create a new branch with git branch and delete one with git branch -d . To rename a branch, use git branch -m . For remote branches, git branch -r shows them; git branch -a shows all local and remote. The -v flag shows the last commit on each branch. Understanding branch naming conventions is crucial—use slashes for hierarchy (e.g., feature/user-auth, hotfix/1.2.3). Branching is cheap in Git because it only stores a 40-character SHA-1 hash. Protect critical branches (like main) with branch protection rules on your remote platform to prevent force pushes or direct commits.

6. git checkout / git switch – Navigate Between Branches

git checkout historically handled both branch switching and file restoration. However, Git 2.23 introduced git switch specifically for branch navigation. Use git switch to move HEAD to another branch. The -c flag creates a new branch and switches to it: git switch -c . For the older git checkout, git checkout -b does the same. Switch back to the previous branch with git switch - or git checkout -. If you have uncommitted changes that conflict with the target branch, Git will refuse the switch. Use git stash to temporarily shelve changes, then git stash pop after switching. Detached HEAD state occurs when you checkout a specific commit instead of a branch—useful for inspection but dangerous for new commits (they become orphaned). Always create a branch from a detached HEAD if you need to keep changes.

7. git merge – Integrate Changes from One Branch into Another

git merge incorporates changes from a source branch into your current branch. Run git switch main then git merge feature-login to merge the feature-login branch into main. Git uses three types of merges: fast-forward (if the target branch hasn’t diverged), recursive (default, creates a merge commit), and octopus (for merging multiple branches). Avoid merge conflicts—they occur when two branches modify the same file lines. Resolve conflicts manually: edit the conflicted files (marked with <<<<<<<, =======, >>>>>>>), then git add them and complete the merge with git commit. For a cleaner history, consider git merge --no-ff to force a merge commit even when fast-forward is possible. If a merge goes wrong, abort with git merge --abort. Merge commits should have clear messages summarizing the integrated changes.

8. git pull – Fetch and Merge Remote Changes

git pull combines git fetch (downloads remote data) and git merge (integrates it into your current branch). The command git pull origin main updates your local main branch with remote changes. By default, it uses a merge; to rebase instead, use git pull --rebase (recommended for a linear history). Always pull before starting new work to minimize conflicts. If you encounter autostash issues, configure git config pull.rebase true globally. For large repositories, git pull --ff-only ensures a fast-forward if possible, failing if a merge is required. Beware of pulling into a dirty working tree—stash changes first. To see what will be pulled before executing, run git fetch then git log origin/main..HEAD to review incoming commits. For simultaneous work on multiple branches, git pull --all fetches updates for all remotes.

9. git push – Upload Local Commits to a Remote

git push sends committed changes from your local repository to a remote. The basic syntax is git push origin . If your local branch hasn’t been pushed before, use git push -u origin to set upstream tracking (the -u flag links your local branch to the remote, enabling subsequent git push without arguments). Use git push --force only when absolutely necessary—it overwrites remote history and can disrupt collaborators; prefer git push --force-with-lease which checks if the remote branch has advanced (safer). To delete a remote branch: git push origin --delete . Push tags with git push origin --tags. For continuous integration, git push can trigger automatic builds. Always verify your push with git log origin/ to confirm the remote matches. If rejected, pull the latest remote changes first.

10. git log – View Commit History

git log displays the commit history of the current branch. Basic output shows each commit’s SHA-1 hash, author, date, and message. Enhance readability with flags: --oneline condenses each commit to one line; --graph shows ASCII branch topology; --decorate adds branch/tag references. For filtering, git log --author="name" filters by author, git log --since="2 weeks ago" shows recent commits, and git log shows commits affecting a specific file. Search commit messages with git log --grep="fix". To see the diff of each commit, add -p. The --stat flag shows file change summaries. For a comprehensive view, git log --all --oneline --graph --decorate visualizes the entire DAG. Understanding git log is critical for code archaeology—why a change was made, when, and by whom. Integrate it into your workflow before code review or debugging.

Leave a Reply

Your email address will not be published. Required fields are marked *