Getting started with Git
Git is a distributed version control system that enables developers to track code changes, collaborate in teams, and manage project history. In Git, you can store different file versions, access them when needed, and work together on a project with no risk of data loss.
Git streamlines complex project work, delivers transparency of changes, and helps avoid teamwork conflicts.
In this tutorial, we will explore the main commands for using Git without the GUI.
- Getting started.
- Working with repositories.
- Working with branches.
- Commits.
- Pushing changes.
- Conflict resolution.
- Additional commands.
Getting started
Install Git:
- Download Git from the official website.
- Run the installation file and follow the setup wizard's prompts.
- During the installation, select to integrate with the command line or PowerShell.
In the terminal, run this command:
sudo apt update && \
sudo apt install git
Note
If you are using a distribution other than Ubuntu or Debian, install Git using your package manager.
-
Install Homebrew by running the following command in the terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
-
Install Git:
brew update && \ brew install git
Working with repositories
Initializing a repository (git init)
Initialization allows Git to index files and start tracking changes in a directory.
-
Create a directory for your project by running this command in the terminal:
mkdir <path_to_directory>
If you need to initialize a repository in an existing directory, skip this step.
-
Navigate to the project directory:
cd <path_to_directory>
-
To initialize the repository, run this command:
git init
This will create Git files in the current directory for Git to treat it as a repository.
Cloning an existing repository (git clone)
To clone an existing repository, run this command:
git clone <repository_link>
This will create a local copy of the remote repository on your computer.
Warning
To clone a private repository, authenticate with a personal access token (PAT) or SSH key.
Updating a local copy of a repository (git fetch and git pull)
To fetch changes from a remote repository, run this command:
git fetch
This will fetch changes into Git’s internal storage; they will be available in remote branches, such as origin/main
, while your local branches remain unchanged.
To merge these changes into your current branch, run the following command:
git pull
Working with branches
Repository branches are separate project copies that enable working on changes independently, without affecting the main version. Branches can be either local or remote. Local branches reside on your computer, while remote branches are hosted on the server and are typically used for team collaboration.
Main branch
In most projects, this branch is referred to as main
or master
. Typically, it stores the stable project version ready for release or deployment. When making changes, avoid pushing them directly to the main branch; instead, create separate branches for new features or bug fixes.
To view all local branches, run the following command:
git branch
The current branch will be marked with *
.
Tip
Also, you can view all repository branches in the SourceCraft interface. To do this, under
Creating a new branch (git branch)
You can use the git branch
command to create an independent copy of your current repository branch and work on changes without affecting the main line of development. Before you start, always run git pull
to make sure your branch and its data are up to date.
To create a new branch, run this command:
git branch <branch_name>
To create a new branch and switch to it right away, run this command:
git checkout -b <branch_name>
Switching between branches (git checkout)
To switch to another branch, run the following command:
git checkout <branch_name>
Merging branches (git merge)
Merging is used to integrate changes from one branch into another, e.g., to update the main branch with fixes or new features. When performing a merge, you join the selected branches into a single unified branch, which will incorporate all the changes.
Once you finish working on a branch, run the following commands one by one to merge it into the main branch:
-
Switch to the target branch, e.g.,
main
:git checkout main
-
Perform the merge:
git merge <name_of_branch_with_changes>
If there are any merge conflicts, you need to resolve them manually.
After a successful merge, the merging branch is typically not deleted automatically and requires manual deletion.
Tip
SourceCraft supports pull requests for safe branch merging with change review and automated checks. For more information, see Creating a pull request in a SourceCraft repository.
Deleting a branch (git branch -d)
If you no longer need a branch, run the following command to delete it:
git branch -d <branch_name>
If your branch contains uncommitted changes that may be lost upon deletion, the command will return an error. To view the current uncommitted changes, run this command:
git status
The command output will show files with changes that have not been staged for commit.
To forcibly delete a branch, run the following command:
git branch -D <branch_name>
Warning
When you forcibly delete a branch, any uncommitted changes will be lost. Make sure nothing important is left unsaved.
Additional actions with branches
To push a branch to the server, run this command:
git push origin <branch_name>
This command will push your local branch to the remote repository, making it available to other contributors.
To view all branches in your repository, run the following command:
git branch -a
You will get a list of all branches in your repository, including those stored on the server.
To restore a previously deleted branch, run this command:
git checkout -b <new_branch_name> <deleted_branch_name>
This will create a new branch based the deleted one, allowing you to restore data that was lost or deleted by mistake.
Commits
After saving changes in the repository files, you need to stage them to be committed.
Commits are snapshots of your files at a specific point in time. They enable you to track the change history and roll back to the versions you need.
Tip
Commit your changes regularly, even minor ones.
Staging changes for a commit (git add)
-
View the unstaged changes:
git status
-
Stage the changes for the commit using one of the following methods:
-
Stage the changes in a specific file:
git add <file_name>
-
Stage all modified files in the current directory:
git add .
-
Stage all modified files in the repository:
git add --all
-
Creating a commit with a message (git commit)
To create a commit with a message describing the changes, run the following command:
git commit -m “Commit message"
Tip
Keep your commit messages short for easier navigation.
Modifying the last commit (git commit --amend -m)
To modify your most recent commit, e.g., to edit the commit message, run this command:
git commit --amend -m "Updated commit message"
Squashing commits (git rebase)
By squashing the few most recent commits, you can make the commit history more concise or logically group related changes.
To achieve this, use interactive rebasing (git rebase -i
) that enables you to select commits for squashing or change their order and contents.
To start rebasing, run this command:
git rebase -i HEAD~N
Where N
is the number of most recent commits to process.
This will open the editor with the list of selected commits. To squash the most recent commits with the older ones, replace pick
with squash
or s
.
Note
Rebasing may cause commit conflicts; you will need to resolve them manually and then run this command to proceed with the rebase:
git rebase --continue
Example of squashing commits
Here is an example of the git rebase -i HEAD~3
command output in the editor:
pick e3a1b35 Correcting a typo
pick 7ac9a67 Adding a new feature
pick 4f5d6e2 Updating documentation
To squash the last three commits into one, replace pick
with squash
(or s
) for the second and third commits.
pick e3a1b35 Correcting a typo
squash 7ac9a67 Adding a new feature
squash 4f5d6e2 Updating documentation
Once done, save the file and close the editor. The selected commits will now be squashed.
Deleting commits (git reset)
To delete the most recent commit, run this command:
git reset --hard HEAD~1
To delete the few most recent commits, run this command:
git reset --hard HEAD~N
Where N
is the number of recent commits to delete.
This will fully delete all changes related to the selected commits from the current branch.
Warning
Be careful when using git reset
. You may lose important changes that have not been committed in other branches or saved elsewhere.
Restoring a commit (git cherry-pick)
To restore a previously deleted commit, you will need its hash (SHA).
A commit hash is a unique short code automatically created for every committed change in the project.
Note
You can only restore a commit that is still in the repository history. If deleted completely, e.g., with git push --force
, the commit cannot be restored.
-
To find the commit you need, check the reference log by running the following command:
git reflog
Command output example:
abc1234 (HEAD -> master) HEAD@{0}: reset --hard HEAD~1 def5678 (branch: master) HEAD@{1}: commit: Added a description ghi9012 HEAD@{2}: commit: Fixed a bug
Where:
def5678
: Commit hash.commit: Added a description
: Commit message.
-
In the command output, find the commit you need by its message.
-
Copy its hash. Normally, this is the first seven to ten characters in the line.
-
Select a restore option:
To a new branchTo the current branchReset the current branch to the commit’s stateTo create a new branch from a commit and switch to it immediately, run the following command:
git checkout -b <new_branch_name> <commit_hash>
Here is an example:
git checkout -b restored-branch def5678
While restoring, you may run into conflicts that require manual resolution.
The commit will be added to the current branch as the most recent one. The changes saved in it will be added to target branch history without affecting other current changes. While adding the commit, you may run into conflicts that require manual resolution.
To restore a commit to the current branch, run this command:
git cherry-pick <commit_hash>
The deleted commit will be restored in the history. The branch will be reset to the commit’s state, discarding all later changes. Be careful, as all current unsaved changes will be lost.
To reset a branch to the specified commit, run the following command:
git reset --hard <commit_hash>
Viewing a commit (git show)
You can view a commit independently of any branch. To view the commit contents directly in the terminal, run this command:
git show <commit_hash>
To exit the viewing mode, press q
.
Pushing changes
The push command uploads changes from your computer to the server, allowing other contributors to see and use them.
Pushing changes (git push)
To push the current changes to a remote repository, run this command:
git push origin <branch_name_in_remote_repository>
Undoing pushed changes (git reset and git push)
To undo your latest changes on the server and restore the branch to its previous state, follow these steps:
-
Reset the local branch to its pre-commit state. To do this, run the following command that deletes the last commit and restores the files to their previous state:
git reset --hard HEAD^
-
Update the remote branch to match your local branch by running the force push command:
git push --force
Be careful: using
--force
may lead to data loss for other project contributors if they have already synced with the remote repository. Any changes they made after synchronization will also be lost. Before running this command, notify your team or make sure nobody will lose crucial data.Note
If your changes are not yet committed, commit them first and then push to the remote repository.
Conflict resolution
A conflict occurs when changes made in a repository overlap.
The causes of conflicts may include:
- Multiple users editing the same files at once.
- Pulling remote repository changes (
git pull
) that conflict with your local edits. - Merging branches (
git merge
) with conflicting changes made to the same lines of code. - Pushing changes (
git push
) to the remote repository that has commits conflicting with your local edits.
Git will report a conflict and indicate conflicting sections in files with conflict markers.
To resolve a conflict, follow these steps:
-
Open the files with conflicts in any text editor.
-
Delete irrelevant text and redundant characters, such as
<<<<<<<
,=======
, and>>>>>>>
. -
Save your changes.
-
Add your changes to the branch:
git add <file_name>
-
Commit the changes:
git commit -m "Commit message"
-
Push the changes:
git push
Additional commands
Command | Use case |
---|---|
git log |
Viewing history. |
git blame <file_name> |
Viewing changes in a specific file. This command shows who made the changes and in which lines. |
git blame -L <start_line>, <end_line> <file_name> |
Viewing changes within a given line range in the selected file. |
git branch |
Viewing all repository branches. The current branch will be marked with * . |
git checkout -- <file> |
Undoing file changes. This command resets the file to its last committed state. |
git diff |
Viewing differences between your local unpushed changes and the latest branch version. |
git diff <branch_name> |
Viewing differences between your local unpushed changes and the latest version of another branch |
git gc |
Optimizing the local repository by freeing up disk space and deleting orphaned or lost data which remains in the repository but is no longer used by current branches. |
git tag |
Creating tags to mark important milestones in the project history, such as releases. |
git remote add <repository_name> <repository_link> |
Connecting your local repository to the remote one to push changes and pull updates. |
git remote -v |
Viewing all remote repositories for the project. |
git stash |
Stashing changes. |
git stash pop |
Restoring stashed changes. |
git reflog |
Listing all changes in the Git logs. By default, the list of HEAD changes is displayed. |