Simplified Git Commands Guide#
Initialize a Git Repository#
- Navigate to the directory you want to track.
- Run the following command:
git initAdding Files or Directories#
- To add files or directories to the staging area, use:
git add <file_or_directory_name>Checking the Current State#
- To see the current state of your repository:
git statusCommitting Changes#
- To save changes to the repository:
git commit -m "Your commit message"Branch Management#
Creating and Switching to a New Branch#
- Use the following command to create and switch to a new branch:
git switch -c my_new_branchThis is easier than using git branch followed by git switch. git branch
Switching Between Branches#
- To switch to an existing branch:
git switch branch_nameViewing Existing Branches#
- To list all branches:
git branchViewing Commit Logs#
- To see commit history:
git log- Optionally, you can specify a branch name:
git log branch_name- For a compact, graphical log, create an alias:
git config --global alias.gitmap "log --oneline --graph --all --decorate --parents"Then use:
git gitmapFetching Updates from Remote Repositories#
- To download objects and refs from a remote repository without merging them into your working directory:
git fetchWorking with Remote Repositories#
- To add a remote repository:
git remote add origin <repository_url>- To list all remote repositories:
git remote -v- To remove a remote repository:
git remote remove <name>git remote add origin https://github.com/your-username/repo_nameMerging Branches#
- To merge a branch into the current branch:
git merge example_branchExample: To merge example_branch into main,ensure you are on main and run the above command.
Creating a New Branch from an Older Commit#
- To create a new branch from a specific commit:
git switch -c new_branch_name old_commit_hashRebasing Branches#
- To reapply commits from
mainonto the current branch:
git rebase mainExample: If you’re on branch example_brach, this command brings changes from main onto example_brach.
git rebase
Resetting Commits#
- To undo commits:
- Use
--softto keep changes in the staging area:
git reset --soft commit- Use
--hardto discard changes:
git reset --hard commitGit Push#
The git push command pushes (sends) local changes to any “remote” - in our case, GitHub. For example, to push our local main branch’s commits to the remote origin’s main branch we would run:
git push origin <branch_name>Git pull#
- To pull changes from a remote repository and update your local repository:
git pull origin <branch_name>What happens when you git clone?#
- It creates a directory for the repository.
- It initializes the repository and fetches its content.
- It automatically sets up the
originremote to point to the repository URL you cloned.
Use the git clone command followed by the repository URL:
git clone <repository-url> <directory-name>Example:
git clone https://github.com/user/repository.gitClone a Specific Branch:
git clone --branch <branch-name> <repository-url>