Basic Git Commands for Daily Use
Working areas
- Working Directory -- The checked out files, as they are sitting on disk in the git repository directory.
- Staging Area -- The files and changes which were added with
git add
and may be commited.
- Local Repository -- The commits sitting on the hidden
.git
folder on your local machine.
- Remote Repository -- The commits stored on the remote machine, which is usually named
origin
.
Creating a new repository
git init
-- Creates a new git repository on the current directory.
git init --bare
-- Creates a new bare git repository on the current directory. A bare repository does not have a working folder, but changes can be pushed into it. Useful for self-hosting git repositories on a VM.
git clone <repo URL>
-- Clones a given repo and sets its url as the origin
remote for pulling and pushing.
Switching branches
git checkout master
-- Switch to the local master
branch.
git checkout <branch name>
-- Switch to an existing local branch.
git checkout -b <branch name>
-- Create and switch to a new local branch.
Staging changes
git status
-- Shows the current branch and lists all modified files in the working directory.
git add .
-- Add all the changes in the current directory and its subdirectories (convenient, but frowned upon since it can lead to commmitting unintended files).
git add <file1> ... <fileN>
-- Add the changes to the listed files. (recommended).
git diff --staged
-- Shows a diff with all the staged changes.
Committing changes
git commit -m "<message>"
-- Creates a local commit with the staged changes.
git commit
-- Opens an editor for editing the commit message. If the commit message file is saved, creates a local commit with the staged changes.
Undoing changes
git restore <file1> ... <fileN>
-- Undoes the changes to the listed files on the working directory.
git reset HEAD~1
-- Undoes the last commit.
Merging/Syncing changes
git pull --all
-- Pulls the latest commits for all branches from the origin
remote.
git push
-- Pushes the latest commits of the current local branch to the origin
remote.
git merge master
-- Creates a commit on the current local branch which merges/applies the latest changes from the local master
branch.