Code

Basic Git Commands: A Cheat Sheet

Basic Git Commands: A Cheat Sheet

Free course: “Quick start in Python»

Learn More

This article introduces Git commands that cover a wide range of tasks. We'll cover in detail the commands for setting up a local repository, managing branches, and effectively interacting with GitHub. These commands will help you streamline your workflow and increase your productivity when using the Git version control system.

If you're already familiar with Git, you can jump directly to the section you need using the link provided. For those just starting out with this version control system, we strongly recommend learning the basic Git commands in sequential order. You might also find it helpful to watch the webinar recording, a link to which will be provided at the end of the article. This will help you better understand Git functionality and master its practical use.

A table of contents is an important element of any document or web page. It allows readers to quickly navigate and find the sections they need. An optimized table of contents contributes to a better perception of information and improves the user experience. A well-written table of contents can also have a positive impact on SEO, helping search engines index pages more effectively.

It's important to keep in mind that the content should be relevant and relevant to the topics discussed in the text. For best results, it's recommended to use keywords that reflect the main idea and purpose of the article. This will not only increase the page's visibility in search engines but also attract a target audience interested in specific topics.

When composing the content, adhere to a logical structure that guides the reader through the material, making it more accessible and understandable. Make sure all section headings and subheadings accurately reflect the content of the sections to facilitate navigation and increase reading interest.

  • Installation and Configuration
  • Installation
  • Configuration
  • Creating a Repository
  • Workflow
  • git add: add files to the index
  • git status: check the status of the repository
  • git commit: add files to the repository
  • git log: view the commit log
  • git show: view a commit
  • git diff: view changes before a commit
  • git difftool: run an external file comparison tool
  • git restore: undo changes
  • git rm: remove files from the index
  • git reset: rollback Commit
  • Branching
  • git branch : create a new branch
  • git branch: view branches
  • git checkout: switch between branches
  • git merge: merge repositories
  • git branch -d : delete a branch
  • Remote Repository
  • git remote add origin url: link a local and remote repository
  • git remote: view remote repositories
  • git remote - v: view remote URLs
  • git push: send changes to a remote repository
  • git pull: get changes from a remote repository
  • Practice Basic Git Commands

An expert is a specialist with deep knowledge and experience in a particular field. Experts play a key role in a variety of fields, including science, technology, business, and the arts. Their unique skills and understanding of the subject matter allow them to provide quality advice and find solutions to complex problems.

Experts often act as consultants, helping organizations optimize processes, increase efficiency, and achieve their goals. In today's rapidly changing world, having an expert is becoming a crucial factor for successful business development and achieving a competitive advantage.

Becoming an expert requires time, effort, and continuous learning. This includes not only theoretical knowledge but also practical experience, making experts indispensable in their field. The role of experts continues to grow, and their influence on decision-making is becoming increasingly significant in a rapidly changing world.

Senior Java Developer at CDEK. We are seeking an experienced specialist with deep knowledge of Java software development. Your task will be to create and support high-quality applications, as well as optimize existing solutions. You will work in a team of professionals, participating in architecture design and the implementation of new technologies. If you are striving for professional growth and want to work in a dynamic environment, CDEK is an excellent place to put your skills and experience to good use. Join us and contribute to the development of cutting-edge IT solutions.

A Skillbox expert, previously serving as a program director, developed the Java course curriculum. His experience and knowledge in programming allow him to create high-quality educational content that meets modern requirements and trends in the IT industry.

Installation and Configuration

Git is not part of the standard software suite for Windows and macOS. It is present on Linux operating systems, but not in all distributions. To ensure that Git is installed on your system, open Terminal and enter the appropriate command. If Git is installed, you will see version information. Otherwise, you will need to install it yourself. Installing Git will allow you to effectively manage versions of your code and simplify collaboration with other developers.

If Git is installed on your device, you will see the available version number. If Git is not installed, the message "Unsupported command: git" will appear. In this case, you need to install and configure Git for further work. Installing Git will allow you to effectively manage versions of your code and collaborate on projects.

Git can be installed in different ways, depending on your operating system. Choose the most appropriate installation method for your system and follow the instructions.

Windows: To install Git, download the installer from the official website git-scm.com. The website offers three installer versions suitable for different systems. Select the appropriate version for your operating system and follow the on-screen instructions to complete the installation. Make sure you download the latest version to get all the new features and bug fixes.

  • standard 32-bit version with the latest build;
  • standalone version for installing Git without an internet connection;
  • portable installer for downloading to a flash drive.

When installing the program, follow the provided instructions and keep the default settings. Please note that you need to select the following options:

  • ✔️ Use Git Bash as default shell - select the Git Bash program;
  • ✔️ Integrate Git with the Windows Shell - agree to work with Git through the command line.

Git can be installed on Windows using the winget package manager from Microsoft. To do this, open PowerShell and enter the following command:

Install the Homebrew package manager on macOS via the Terminal program. Homebrew is a powerful tool that simplifies the installation and management of programs and libraries on your system. To get started, open Terminal and run the command provided on the official Homebrew website. After successful installation, you will be able to easily add and update various packages, significantly simplifying your work with macOS.

To install Git on macOS, you can check out alternative methods on the official website git-scm.com. It presents various approaches, including using Homebrew, installation via binaries, and other methods that will help you quickly and efficiently set up Git on your computer.

Linux. To install Git, go to git-scm.com and copy the command corresponding to your Linux distribution's package manager into Terminal. Here are some example commands for various distributions:

If you are using macOS or Linux, after installing Git, open Terminal. For Windows users, you need to launch Git Bash. In these interfaces, we will execute all the necessary commands for working with Git.

On the command line, enter your name and email address—this information will allow other developers to contact you to discuss commits. Each commit you make will be signed with the specified nickname and email address, simplifying team collaboration and increasing project transparency. Make sure you enter the correct information to avoid problems identifying your changes.

Your first and last name must be written in Latin characters, separated by a space, and enclosed in quotation marks. This is important for the correct formatting of documents and registration in various systems. Follow this rule to avoid errors and misunderstandings when processing your data. Correct spelling of your first and last name will ensure accuracy and easy identification.

Your email address must be written in quotation marks to ensure the correct formatting during processing. This prevents errors and ensures that the email address is correctly interpreted by the system. Using quotation marks is important when working with email, as they help separate the address from the rest of the text and prevent possible misunderstandings. Please note that proper formatting of the email address improves user interaction and increases the level of trust in your content.

Enabling automatic color support in your repository allows you to visually distinguish different file types. This feature simplifies navigation and project management, since each file type will be displayed in a unique color. Setting up this option makes it easier to work with code and improves the perception of the project structure. Use automatic color support to make your repository more organized and easier to perceive.

You should check that the data was successfully added and is displayed correctly.

When you run the request, your profile settings will be displayed in the command line.

Creating a repository

Go to your project directory and run the command to connect Git. This will allow you to effectively manage versions of your code and track changes in the project. Using Git will ensure reliable change history and simplify project collaboration.

After executing the command, you will see a message about repository initialization. This means Git has started tracking your project files and will save changes in the hidden .git folder. If you need to create a new repository, simply repeat this procedure. Git allows you to manage an unlimited number of repositories on a single computer, making it a convenient tool for developers and teams working on various projects.

The command line allows you to not only work effectively with Git but also easily navigate your project. Below is a list of essential commands that will be useful for navigating and managing your project. These commands will help you quickly find the files you need, change directories, and optimize your workflow. Using the command line in Git can significantly speed up the execution of tasks and improve overall productivity when working with projects.

  • pwd — view your current location;
  • ls — list folders and files in the current directory where the command was executed;
  • ls -a — list open and hidden folders and files in the current directory where the command was executed;
  • cd ~ — go to the home directory of the current user;
  • cd .. — go up one level in the file system hierarchy;
  • cd folder_name — go to the selected folder;
  • mkdir folder_name — create a folder with the specified name.

Read also:

Basic commands and hotkeys for the Linux terminal, as well as Unix, macOS, and FreeBSD, play a vital role in working effectively with these operating systems. Knowing these commands allows users to quickly perform tasks and manage the system.

Linux terminal commands include basic operations such as navigating the file system, managing files and folders, installing and removing programs, and viewing system information. For example, the ls command allows you to view the contents of a directory, and the cd command is used to change directories. The touch and mkdir commands are used to create new files and folders.

Keyboard shortcuts significantly speed up working in the terminal. For example, Ctrl+C interrupts the current command, and Ctrl+Z pauses the process. Using Ctrl+R allows you to search through previous commands, which is very convenient for repeating frequently used queries.

To work more efficiently in the terminal, it is also important to learn process management commands, such as top to display active processes and kill to terminate unnecessary tasks. These tools help maintain optimal system performance.

Knowing basic terminal commands and keyboard shortcuts is a key skill for Linux, Unix, macOS, and FreeBSD users. This not only makes routine operations easier but also allows you to gain a deeper understanding of how the operating system works.

Workflow

When using Git, you'll add files to the index, check the status of your repository, create commits, view the change history, and roll back changes when necessary. These basic operations allow you to effectively manage versions of your code, track changes, and ensure a reliable workflow. Mastering these Git features is key to successful teamwork and solo programming.

When you create a file in a project, Git classifies it as untracked. Such files cannot be added to the repository without first being staged. This staging process is handled by the index—the staging area that serves as the link between the working directory and the repository. To stage files, use the git add command. This action allows Git to start tracking changes in the file and prepare it for the next commit.

You can add a single file, several files, or all files at once to the index. Once added to the index, files are staged. This is an important step in the version control workflow, allowing you to organize changes before committing them to the repository. Proper use of the index helps avoid accidental errors and simplifies project version management.

The git add command has many variations. For example, git add *.js adds all files with the .js extension from the current directory to the index. For detailed documentation for any command, use the built-in help.

The git status command provides information about the state of your repository. It displays which files are untracked, which are in the index, and what changes have been made to the stored files. Using this command allows you to quickly monitor changes in your project and manage file versions more effectively. Regularly using git status helps avoid confusion and ensures you're always up-to-date on the current state of your project.

When all files are ready to be stored, they should be moved from the index to the repository using the git commit command. To do this, use the -m option, followed by a commit message enclosed in quotation marks. The message is typically written in Latin and should clearly reflect the essence of the changes made. This will aid in subsequent tracking of the change history and improve communication with the development team.

Commit messages are essential because they help developers navigate the project. There is a special document called the "Commit Convention," in which developers have agreed on the rules for writing comments. The main purpose of these messages is to clearly reflect the changes made. For example, it is important that the commit text clearly indicates what exactly was done. Proper communication formatting helps improve project documentation and simplifies the collaboration process.

Added my first commit.

Fixed bug number XXXXX.

Working on the index.html file is an important stage in website development. This file serves as the main entry point for users and search engines, so its optimization is critical. When editing index.html, consider the correct use of semantic markup to ensure better page indexing. It is also important to apply appropriate title tags, meta tags, and alt attributes for images. These elements will help improve the site's visibility in search engines and provide a convenient user experience. It is important to keep the code clean to ensure fast page loading and a better user experience.

I designed the header for the website's main page. This is an important element that ensures easy navigation and attracts user attention. The header includes the logo, menu, and key links, which helps improve the user experience and increase visibility in search engines.

If you don't use the -m option, you'll be in a text editor after pressing Enter. In this editor, you'll write a message, save it, and exit. However, in Vim, the process can be more complex.

While working with Git, you may find yourself changing a file that's already committed. In this case, you can create a new commit, bypassing the index, using the -a option. This allows you to automatically add changes to tracked files to the commit, simplifying the process and saving time. Using this option is especially useful when you're confident in your changes and want to commit them to the repository quickly.

It's common to make a mistake in your commit message while rushing. To correct this, you can use the —amend— option, which allows you to change the message of the last commit. This is a useful tool for maintaining clarity and accuracy in your project history. Using this feature helps avoid confusion and improves the structure of your repository.

The git log command displays the commit history in reverse chronological order. With it, you can view the hashes, messages, dates, and author handles of each commit. This is an essential tool for tracking changes in a project, allowing you to analyze edits and understand their context. Using git log helps developers effectively manage code versions and track changes, which is critical for successful teamwork.

The git log command offers many options that affect the formatting and display of the commit log. One useful feature is to display information about each commit on a single line. To achieve this, you need to hide the date, author name, and reduce the length of the commit hash. These settings make viewing the log more compact and convenient for analyzing changes in the project.

The git show command provides information about a specific commit. There are two main blocks of output: the first contains metadata such as the author, date, and commit ID, while the second is a list of the changes made in that commit. The git show command is a useful tool for analyzing project history and tracking edits.

Entering the git show command without specifying a hash displays information about the contents of the latest commit in the repository. This command is useful for quickly viewing the changes made in the latest commit, including the modified files, their contents, and commit metadata. Using git show allows developers to effectively track changes and analyze project history.

The git diff command allows you to see the changes between the latest commit and the current state of the repository. It compares the latest commit with all untracked files that have not yet been added to the index. This is a useful tool for developers, allowing them to track changes before committing them and helps avoid accidental errors. Using git diff, you can quickly assess what changes have been made to a project and decide on what to do next with the code.

To analyze changes to a file, you can add its name and compare the current contents with the last commit. This will identify all changes made and track the editing history. Comparing a file with the last commit is an important tool for version control and simplifies the process of working with code.

As an alternative to the file name, you can use the commit hash. You can also add the —staged— option to compare the version of the code after the last commit with the current state of the repository. This will analyze all files in the index and identify changes that have not yet been committed. This approach helps you track changes in the project and manage code versions more effectively.

The git difftool command functions similarly to the git diff command, comparing files and identifying their differences. However, git diff outputs results in text format, while git difftool uses graphical interfaces for visual comparison. This command launches external applications such as Beyond Compare, vimdiff, or Meld, which provide convenient tools for analyzing changes. To start using git difftool, install one of the mentioned applications, then read the git difftool documentation and practice displaying differences between files. This will greatly simplify your work with versions and help you quickly identify changes in the code.

The git restore command allows you to revert a file to the state of the last commit, undoing all changes made. If the file has not been added to the stage, the command will restore it to its original state. In case the file is already in the staged state, you must use the —staged— option to restore it. This command is useful for managing changes in a project and helps maintain a clean commit history.

The git rm command is used to remove files that were mistakenly added to the stage. After executing this command, the file will be removed from both the index and the local project folder. If your goal is to remove the file only from the index, without physically deleting it from the filesystem, you should use the git rm command with the —cached— option. This option allows you to keep the file in the working directory, but exclude it from version control tracking.

The git reset command provides the ability to undo one or more commits and return the project to a specific state from the past. It is important to use this command with caution, as it can irreversibly change the project history. Proper use of git reset can help keep your repository clean and tidy, but you should be aware of the potential impact on collaboration, especially if the changes have already been published. Use git reset to manage your commit history, but always carefully evaluate the need for this operation.

You can choose from three modes: —soft, —mixed, and —hard. Each of these modes offers unique settings and capabilities, allowing you to tailor the experience to your needs. Choosing the right mode will help streamline the process and achieve the best results.

In —soft—mode, the project reverts to the selected commit, with all subsequent commits moved to the index. This allows you to immediately create a new commit and rewrite the project history, while keeping the original files unchanged. This mode is useful for adjusting the change history without affecting the current state of the files.

In —mixed—mode, reverted files are moved to the untracked zone. In this state, you have the option to modify, delete, or revert these files back to the index. This approach gives you flexible change management in your project, giving you control over which files should be included in the next commit.

In —hard—mode, the project reverts to the specified commit, with all subsequent commits permanently deleted. This mode is useful when you need to completely undo changes made after a certain point in the project's history. It is important to use it with caution, as it is not possible to restore deleted commits.

Before running the git reset command, it is highly recommended to create a backup of your project to avoid possible data loss or accidental file deletion. This will help preserve the current version of your project and prevent unwanted consequences.

Branching

All development in Git is done through branches. Branches play a key role in storing commits and organizing them into a sequence. Moving along a branch from one commit to the next allows you to effectively track changes in the project. As you work with branches, you will frequently create, view, rename, switch between them, merge, and delete. These are important operations that help keep your repository organized and facilitate collaboration on the project. Using branches in Git significantly improves version control and adds structure to the development process.

After the first commit, Git automatically creates the first branch, which typically contains a stable version of the project for end users. Developers can create separate branches for other tasks using the git branch command. This helps organize their workflow, manage changes efficiently, and facilitates team collaboration by allowing them to work on different features or fixes without affecting the main stable version of the project.

The branch name should clearly reflect its content. For example, if the name includes the word "bugfix", it means that the branch is intended for bug fixes. If the name includes "feature", it indicates the development of a new feature. Names such as "test10.24" are meaningless and should be avoided. Choosing appropriate branch names not only makes it easier for your team to understand your work, but also promotes more effective project management and makes it easier to find relevant changes.

A poorly named branch can be renamed to something more appropriate. Renaming a branch will help better reflect its content and simplify navigation. This is especially important for project usability and improved structure. Make sure the new name is descriptive and reflects the branch's purpose.

The git branch command provides users with a complete list of all available branches in a project. It also marks the currently active branch with an asterisk, making it easy to identify which branch you're currently on. This is especially useful for version control and team coordination. Using git branch simplifies the process of navigating between branches and significantly speeds up working with the Git version control system.

The git checkout command is used to switch between branches in the Git version control system. With this command, you can easily switch to a different branch, allowing you to work with different versions of your project. Git checkout also allows you to restore files and navigate to specific commits, providing flexibility in code management. To switch to a different branch, simply enter the git checkout command followed by the name of the desired branch. Proper use of git checkout helps developers effectively manage their projects and maintain order in their codebase.

You can create a new branch and immediately switch to it with a single command. This simplifies and improves the process of working with code versions. This approach is especially useful during development, when you need to quickly switch between tasks and changes. Using this command will help you optimize your workflow and improve version control in your project.

The git checkout command has a more modern equivalent that simplifies the process of working with branches and files in the repository. This alternative allows users to easily switch between branches and restore files without having to use legacy commands. Modern approaches to version control in Git make working more intuitive and efficient, significantly simplifying the process of development and project collaboration. Using new commands improves productivity and minimizes errors, which is especially important for team development.

The git switch command is a safer option for switching between branches and is ideal for beginners. Before each switch, it automatically checks the state of the working directory and prevents the switch if it could lead to data loss. This approach avoids unwanted errors and protects your work. Using git switch helps beginners gain confidence in working with version control systems, minimizing risks and simplifying the branch management process.

The git merge command is used to integrate changes from one branch into another. This process, known as merging, culminates in the creation of a common commit that combines both branches. This commit allows you to track the change history of each branch, simplifying project management and providing transparency in code development. With git merge, developers can easily combine new features and fixes, keeping the code in the project up-to-date and consistent.

After merging, the secondary branch is no longer needed and can be deleted. This helps keep the repository tidy and simplifies version control. Removing irrelevant branches also prevents confusion and makes it easier to work with the main code.

Remote Repository

In the previous sections, we learned how to use Git on a local computer. Now we need to create a remote repository, which will allow us to share code with other developers and provide a backup storage for our project. A remote repository can be created on various platforms, but the most popular are GitHub and GitLab. In this case, we will focus on GitHub.

To get started with GitHub, you need to register and set up SSH keys, which ensures a secure connection to the platform. Once this setup is complete, you can move on to working with the remote repository. Properly configuring SSH keys not only improves security but also simplifies the authentication process, allowing you to effectively manage projects on GitHub.

Using the command line, navigate to your project directory on your computer. Then, run the git remote add command to create a connection between your local repository and the remote repository on GitHub. This will allow you to synchronize changes and manage collaboration on the project.

The command requires two parameters: the name of the remote repository and its address. The address can be found on your profile page in the SSH tab. Make sure you copy the address correctly to ensure successful interaction with the repository.

If you actively use GitHub, your local repository may contain many remote repositories. To view a list of these repositories, simply run the git remote command. This will allow you to see the names of all connected remote repositories and simplify the process of sorting and deleting unnecessary ones. Organizing your remote repositories will help you keep your workspace clean and manage your projects effectively.

The git remote command displays the names of the remote repositories associated with your local repository. For additional information, you can use the -v option, which will show the remote URLs. These URLs will help you track changes and interact with remote repositories more effectively. Using the git remote command with the -v option is an important part of working with version control systems, as it allows you to better manage your projects and track their status.

The git push command is used to transfer changes from a local repository to a remote one. It updates the remote branch, synchronizing it with the local changes. This is an important step in the process of collaborating on projects, allowing other team members to access the latest code updates. Proper use of git push ensures effective version control and helps simplify team collaboration.

The first time you push, you must use the command with the -u option. This option links the local and remote branches, ensuring they are synchronized for future operations. Subsequent pulls do not require the -u option, since the links between the branches are already established.

The git pull command allows you to download the latest changes from a remote repository and update your local copy of the project. This command combines two operations: git fetch, which retrieves data from the remote repository, and git merge, which merges these changes into the current branch. Using git pull keeps the local and remote repositories in sync, allowing developers to stay up-to-date and work with the latest versions of code.

Practice Essential Git Commands

Practice under the guidance of Skillbox experts. Our professionals will help you develop skills and confidence in your chosen field. Join us to gain practical experience and new knowledge that will help you advance your career.

Daniil Pilipenko, CEO of the SymbioWay IT recruitment center, held a webinar on the Git version control system. During the event, he provided a detailed overview of key commands such as git status, git add, git commit, git log, git branch, and git clone. Webinar attendees gained practical knowledge on how to effectively use these commands to manage projects and improve workflow in software development.

Learn more about coding and programming in our Telegram channel. Subscribe to stay up-to-date with helpful tips and interesting content!

Rework the text while maintaining the main theme. Optimize it for SEO by adding keywords and phrases that will improve search engine visibility. Avoid using emojis and unnecessary symbols. Don't add sections with numbers or symbols. Please provide plain text only.

  • Silly questions about Git and version control systems
  • What is Git: explained with diagrams
  • Instructions: uploading a project to GitHub without the command line