Git Command Cheat Sheet

Git Command Cheat Sheet

Картинка к публикации: Git Command Cheat Sheet

Git

Git is a version control system that allows you to efficiently manage and track changes in source code and other files. Git enables multiple people to work on the same project simultaneously, making changes and merging them into a single version. It is one of the most popular version control systems and is widely used in various projects, including software development, scientific research, websites, and much more.

Git's history began in 2005 when Linus Torvalds, the creator of the Linux kernel, started developing a new version control system to manage the Linux kernel's source code. He was dissatisfied with the existing version control systems at the time, which were either inefficient or complicated to use. Git was created as a fast, efficient, and easily extensible tool for handling large projects with a distributed architecture.

Since then, Git has not only become popular among Linux developers but has also quickly spread worldwide, becoming one of the most widely used tools across various fields. Git is free and open-source software, allowing anyone to use, modify, and distribute it at no cost.


Basic Repository Operations

git init

The git init command is used to create a new local Git repository. After running this command, Git creates a new .git subdirectory in the current directory, which contains all the Git files necessary for version control in that repository.

Command Syntax:

git init [--bare] [<directory>]
  • --bare: Defines the repository as "bare," meaning it has no working directory. This is used for creating remote repositories.
  • <directory>: Specifies the directory where the local repository will be created. If not provided, the repository is created in the current directory.

Example Usage:

$ cd my_project
$ git init
Initialized empty Git repository in /path/to/my_project/.git/

This command creates a new local Git repository in the current my_project directory. Git creates a .git subdirectory and initializes it with the necessary files for version control.

To create a "bare" remote repository, use the --bare flag:

$ mkdir my_repo.git
$ cd my_repo.git
$ git init --bare
Initialized empty Git repository in /path/to/my_repo.git/

This command creates a new remote Git repository in the my_repo.git directory. The --bare flag indicates that this is a bare repository, meaning it does not have a working directory.

The git init command also supports other options and flags for various scenarios. For example, the --template flag allows you to specify a custom initialization template, and the --separate-git-dir option lets you place the repository in a different directory. You can view all available options and flags in the Git documentation.


git clone

The git clone command is used to create a local copy of a remote Git repository. This allows you to obtain a project copy on your local machine and start working with it.

Command Syntax:

git clone <repository-URL> [<local-folder-name>]
  • <repository-URL>: The URL of the remote Git repository.
  • <local-folder-name> (optional): The name of the local folder where the repository will be cloned. If not specified, Git automatically creates a folder with the repository's name.

Example Usage:

git clone https://github.com/username/repo.git

This command creates a local copy of the remote repo repository located in the username account on GitHub, placing it in a folder named repo.

To specify a custom name for the local folder, add it after the repository URL:

git clone https://github.com/username/repo.git myproject

This command clones the remote repo repository into a folder named myproject. If the myproject folder already exists, Git will display an error message and will not clone the repository.


Working with Changes

git add

The git add . command is used to add changes to the Git index. The index is an intermediate layer between the working directory (where your files are) and the Git repository (where changes are stored). When you make changes to files in the working directory, they are not automatically added to the index. To add changes to the index, you need to use the git add command.

Command Syntax:

git add .

This command adds all modified files in the working directory to the index.

Example Usage:

  1. Create a new file named file.txt in your working directory and add some text to it.
  2. Run the git status command to see the changes in the working directory:

    $ git status
    On branch master
    Untracked files:
      (use "git add <file>..." to include in what will be committed)
        file.txt
    
    nothing added to commit but untracked files present (use "git add" to track)
    

    You can see that file.txt is not yet tracked by Git.

  3. Use the git add . command to add all modified files in the working directory to the index:

    $ git add .
    
  4. Run git status again to see the changes in the index:

    $ git status
    On branch master
    Changes to be committed:
      (use "git restore --staged <file>..." to unstage)
        new file:   file.txt
    

    Now, file.txt has been added to the index.

  5. Commit the changes to the Git repository:

    $ git commit -m "Added file.txt"
    [master 0e3b0a7] Added file.txt
     1 file changed, 1 insertion(+)
     create mode 100644 file.txt
    

    You can see that file.txt has been successfully added to the Git repository.

The git add . command is very useful when you need to add many files to the index at once. However, be cautious when using this command, especially in large projects with many files. In some cases, you may need to selectively add files to the index to avoid accidentally including unnecessary files.


git commit

The git commit command is used to save changes made in your local repository to the commit history. Each commit in Git has a unique identifier, date and time, author name, email, and a message describing the changes.

Command Syntax:

git commit -m "<commit-message>"
  • -m: Stands for "message."
  • <commit-message>: A brief description of the changes made in the commit.

Example Usage:

  1. Add changes to the index using the git add command (e.g., git add filename.txt or git add . to add all modified files).
  2. Make a commit using the git commit command with a commit message in quotes to describe what was changed:

    git commit -m "Added new README.md file"
    

    After executing the command, Git saves the changes to the commit history, and the commit message will appear in the list of commits.

It's important to note that each commit should have a unique message that describes the changes it contains. This helps you and your team members understand what was changed and why.

Additionally, the git commit command can be further customized using various options, such as -a (automatically adds all modified files to the index) or --amend (used to modify the last commit). For more detailed information on available options for the git commit command, refer to the Git documentation.


git diff

The git diff command is used to view differences between file versions in the repository. It shows what changes have been made to files since the last commit.

Basic Command Syntax:

git diff [<options>] [<source>] [<target>]
  • <source>: Defines the starting point of the changes to display differences.
  • <target>: Defines the endpoint of the changes to display differences.
  • <options>: Additional flags that modify the command's behavior.

Common git diff Flags:

  • --cached: Compares changes between your index (what will be in the next commit) and the last commit.
  • --stat: Shows statistics of changes for each file.
  • --color: Displays differences using colors for better readability.

Examples of Usage:

  • git diff: A simple run of the command shows differences between your working copy and the last commit.
  • git diff --cached: Shows differences between your index and the last commit.
  • git diff HEAD: Shows differences between your working copy and the last commit.
  • git diff HEAD~2 HEAD: Shows differences between the last two commits.
  • git diff --stat: Shows statistics of changes for each file.
  • git diff --color: Shows differences using colors.

Additionally, you can use git diff to compare any two commits, branches, or tags in the repository. For example, git diff branch1..branch2 will show differences between the two branches branch1 and branch2.


git revert

The git revert command is used to undo a specific commit by creating a new commit that reverses the changes introduced by the targeted commit. This makes the command safe for use in shared repositories because it does not alter the commit history.

Command Syntax:

git revert <commit>
  • <commit>: The hash identifier of the commit you want to revert.

Example Usage:

  1. View the commit history with git log --oneline:

    $ git log --oneline
    d3b3d43 Commit C
    786f7f8 Commit B
    12556fa Commit A
    
  2. Revert a specific commit:

    $ git revert d3b3d43
    

    This command creates a new commit that reverses the changes made by the commit with the hash d3b3d43.

Flags:

  • --no-commit: Applies the changes but does not create a new commit. This allows you to review the changes before committing them.
  • -m parent-number: Used if the commit has multiple parent commits (such as in a merge). It specifies which parent commit to use when performing the revert.

Example with --no-commit Flag:

$ git revert --no-commit d3b3d43
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
        modified:   file.txt

This command reverts the changes made by the commit d3b3d43 and adds them to the index. However, a new commit is not created until you run git commit.


git stash

The git stash command is used to temporarily save all uncommitted changes in your working directory and index (i.e., staged changes) so you can work on a clean codebase. This is particularly useful when you need to quickly switch branches without losing your current work.

Command Syntax:

git stash push [-m <message>] [--include-untracked] [--keep-index]

Common Flags:

  • -m <message> or --message <message>: Adds a custom message to the stash for easier identification.
  • --include-untracked: Includes untracked files in the stash (i.e., new files that have not been added to the index).
  • --keep-index: Keeps the changes that have already been added to the index (staged changes) in your working directory after creating the stash.

Example Usage:

$ git stash push -m "Temporary changes before switching branches"

After executing this command, all current changes in the working directory and index are saved to the stash stack, and your working directory returns to the state of the last commit. You can later retrieve your changes using git stash pop or git stash apply.

The git stash command allows you to effectively manage temporary changes without disrupting your main work and without needing to create commits for unfinished work.


git stash pop

The git stash pop command is used to apply the changes from the most recent stash entry to your current working directory and remove that stash from the stash stack. This allows you to restore the changes you temporarily saved with git stash push and continue working on them.

Command Syntax:

git stash pop [--index] [<stash>]

Common Flags:

  • --index: Applies not only the changes in the working directory but also restores the index (staged changes) to the state they were in when the stash was created. This is useful if you want to maintain the separation between staged and unstaged changes.
  • <stash>: Specifies a particular stash entry to apply, using its name (e.g., stash@{0}). If not provided, the most recent stash (stash@{0}) is used by default.

Example Usage:

$ git stash pop

After running this command, the changes from the latest stash entry are applied to your current working directory, and the stash entry is removed from the stack. If there are conflicts during the application, you will need to resolve them manually, and the stash entry will not be removed until all conflicts are resolved.

Using git stash pop allows you to easily return to working on temporarily shelved changes, providing efficient management of your workflow.


git stash apply

The git stash apply command is used to apply the changes from a stash entry to your current working directory without removing that stash entry from the stash stack. This allows you to restore the changes you temporarily saved and continue working on them while keeping a copy in the stash stack for potential future use.

Command Syntax:

git stash apply [--index] [<stash>]

Common Flags:

  • --index: When used, the command attempts to restore not only the changes in the working directory but also the staged changes that were saved in the stash. This helps maintain the separation between staged and unstaged changes at the time the stash was created.
  • <stash>: Specifies a particular stash entry to apply, using its identifier (e.g., stash@{0}). If not provided, the most recent stash (stash@{0}) is applied by default.

Example Usage:

$ git stash apply

This command applies the changes from the latest stash entry to your current working directory. Unlike git stash pop, the stash entry remains in the stash stack. If conflicts arise during the application, you must resolve them manually. The applied stash entry is not removed from the stack, allowing you to reuse it later or apply it to another branch.

Using git stash apply provides flexibility in managing temporarily saved changes, enabling you to continue work without removing the stash entry, which can be useful for testing changes across different branches.


git stash list

The git stash list command displays a list of all stash entries that have been created in the repository using the git stash push command. This list allows you to view all temporarily saved changes, making it easy to identify and select the desired stash entry for application or removal.

Command Syntax:

git stash list

No additional arguments are required for this command.

After running the command, you will see a list of all stashes saved in your repository. Each stash entry will have a unique identifier in the format stash@{N}, where N is the stash's position in the stack, along with a brief description that includes the branch name from which the stash was created and any message added when the stash was created.

Example Output:

stash@{0}: On master: feature added
stash@{1}: On develop: bug fix

This output indicates that there are two saved stashes in the repository: the first (stash@{0}) contains changes with the message "feature added" from the master branch, and the second (stash@{1}) contains changes with the message "bug fix" from the develop branch.

Using the git stash list command provides a convenient way to view and manage your temporary changes, allowing you to easily choose the stash entry you want to apply (git stash apply) or remove (git stash drop).


Managing History

git reset

The git reset command is used to undo changes in your local repository. It allows you to reset your working directory to a specific commit, altering the commit history and/or the state of the index (staging area). Depending on the options used, git reset can modify the HEAD (current commit), the index, and the working directory.

Command Syntax:

git reset [--soft | --mixed | --hard] <commit>

Main Options:

  • --soft: Resets HEAD to the specified commit but leaves the working directory and index unchanged. Changes made after the specified commit remain in the index, ready to be committed.
  • --mixed (default): Resets HEAD and the index to the specified commit but leaves the working directory unchanged. This means that changes that were staged are unstaged but remain in the working directory as untracked changes.
  • --hard: Resets HEAD, the index, and the working directory to the specified commit. All changes in the working directory and index are lost. Use this option with caution.

Example Usage:

  1. To undo the last two commits and return the changes to the working directory as unstaged changes:

    $ git reset --mixed HEAD~2
    
  2. To completely remove the last two commits, including all changes in the working directory:

    $ git reset --hard HEAD~2
    

Using the git reset command provides a powerful tool for managing your commit history and the state of your index. It allows you to correct mistakes in your commit history or undo changes before they are published to a remote repository. However, using the --hard option can lead to data loss, so it is recommended to ensure that no important uncommitted changes are present before using it.


git log

The git log command is used to view the commit history in a Git repository. It displays a list of commits in reverse chronological order, starting with the most recent.

Example Usage:

git log

This command shows a list of all commits in the repository, from the most recent to the oldest. Each commit includes its SHA-1 hash, the author's name, the date and time of the commit, and the commit message.

Common git log Flags:

  • --oneline: Displays each commit on a single line, showing only its SHA-1 hash and commit message.
  • --graph: Displays the commit history as a graph, making it easier to visualize branching and merging history.
  • --author=<name>: Shows only commits made by the specified author.
  • --since=<date>: Shows only commits made after the specified date.
  • --until=<date>: Shows only commits made before the specified date.
  • -n <number>: Shows only the specified number of most recent commits.
  • --grep=<string>: Shows only commits that contain the specified string in their commit messages.

Example Usages:

  1. To view commits made since January 1, 2022:

    git log --since=2022-01-01
    

    This command lists all commits made after January 1, 2022.

  2. To view commits by a specific author:

    git log --author="John Doe"
    

    This command lists all commits made by the author named "John Doe."

  3. To search for commits that include the word "bug" in their messages:

    git log --grep="bug"
    

    This command lists all commits that contain the word "bug" in their commit messages.


git checkout

The git checkout command is used to switch between branches, inspect commits, and revert changes. It allows you to navigate between different states of your repository.

Common Flags:

  • -b: Creates a new branch and switches to it. For example, git checkout -b new-branch creates a new branch named "new-branch" and switches to it.
  • -f: Forces the checkout, overwriting any local changes that have not been committed. Use this flag only in extreme cases.
  • -p: Allows you to interactively select specific changes to revert.

Example Usages:

  1. Switching to a Branch:

    git checkout main
    

    This command switches you to the main branch.

  2. Creating a New Branch and Switching to It:

    git checkout -b new-branch
    

    This command creates a new branch named new-branch and switches to it.

  3. Switching to a Specific Commit:

    git checkout 2a3e8c9
    

    This command switches you to the commit with the specified hash identifier.

  4. Reverting Changes in a File:

    git checkout myfile.txt
    

    This command discards changes in the myfile.txt file and restores it to the last committed version.

  5. Restoring Specific Changes Interactively:

    git checkout -p myfile.txt
    

    This command allows you to review changes in the myfile.txt file and selectively choose which changes to revert.

Using the git checkout command enables you to navigate through different branches and commits, as well as manage changes in your working directory effectively.


Managing Branches

git branch

The git branch command is used to view, create, and delete branches in a Git repository. A branch is a separate line of development that can have its own set of commits.

Common git branch Flags:

  • -a: Shows all branches, including remote branches.
  • -d: Deletes a branch. This command only deletes branches that have been merged into the current branch.
  • -D: Deletes a branch without checking if its changes have been merged into the current branch.
  • -m: Renames the current branch.
  • -r: Shows all remote branches.

Example Usages of git branch:

  • Viewing the List of Branches:

    git branch
    

    This command lists all local branches in the repository. The current branch is highlighted with an asterisk (*).

  • Creating a New Branch:

    git branch new-branch
    

    This command creates a new branch named new-branch without switching to it.

  • Renaming the Current Branch:

    git branch -m new-branch-name
    

    This command renames the current branch to new-branch-name.

  • Deleting a Branch:

    git branch -d branch-to-delete
    

    This command deletes the branch named branch-to-delete. It will only delete the branch if it has been merged into the current branch.

  • Viewing Remote Branches:

    git branch -r
    

    This command lists all remote branches associated with the repository.

The git branch command allows you to manage branches within your repository, facilitating team collaboration and organized project development. It also helps in controlling the history of changes in your project.


git merge

The git merge command is used to combine changes from one branch into another. It is typically used to integrate bug fixes or new features from a separate branch into the main branch.

Command Syntax:

git merge <branch-name>
  • <branch-name>: The name of the branch whose changes you want to merge into the current branch.

Example Usage of git merge:

First, switch to the branch you want to merge changes into:

git checkout master

Then, execute the merge command specifying the branch you want to merge from:

git merge feature-branch

In this example, changes from the feature-branch are merged into the current master branch.

Common git merge Flags:

  • --no-ff: Disables fast-forward merging, creating a merge commit even if the changes could be applied with a fast-forward. This helps preserve the history of feature branches.
  • --abort: Aborts the current merge process and returns the repository to its previous state.

Example Usages with Flags:

  • Using the --no-ff Flag:

    git merge --no-ff feature-branch
    

    This command merges feature-branch into the current branch by creating a new merge commit, ensuring that the history of the feature-branch is preserved.

  • Using the --abort Flag:

    git merge --abort
    

    This command aborts the ongoing merge process and reverts the repository to its state before the merge began.


git rebase

The git rebase command is used to reapply commits from the current branch onto another branch or a specific commit. This means that the changes from the source branch are applied on top of the target branch's commits.

Common git rebase Flags:

  • -i or --interactive: Launches an interactive mode that allows you to reorder, squash, or edit commits during the rebase process.
  • -m or --merge: Used when rebasing a merge branch to handle merge commits correctly.
  • --onto <branch>: Rebases the current branch onto the specified branch.

Example Usages of git rebase:

  • Rebasing the Current Branch onto Another Branch:

    git checkout feature-branch
    git rebase main
    

    In this example, the feature-branch is rebased onto the main branch. This applies the changes from main on top of the commits in feature-branch.

  • Rebasing the Current Branch onto a Specific Commit:

    git checkout feature-branch
    git rebase abc123
    

    Here, feature-branch is rebased onto the commit with the hash abc123. This means that changes from commit abc123 and all commits after it will be applied on top of feature-branch.

  • Using Interactive Mode:

    git checkout feature-branch
    git rebase -i main
    

    This command starts an interactive rebase of feature-branch onto main, allowing you to modify the commit history by reordering, squashing, or editing commits.

  • Rebasing a Merge Branch:

    git checkout merge-branch
    git rebase -m main
    

    In this example, the merge-branch, which is a merge branch, is rebased onto the main branch. The -m option ensures that merge commits are handled correctly during the rebase.


Working with Remote Repositories

git fetch

The git fetch command is used to retrieve changes from a remote Git repository without merging them into your local branches. This command allows you to update your local repository with information about new branches and commits that exist in the remote repository but are not yet present locally.

Command Syntax:

git fetch [<remote>] [<refspec>...]
  • <remote>: The name of the remote Git repository (e.g., origin). If not specified, Git uses origin by default.
  • <refspec>: The names of branches and tags you want to fetch from the remote repository. If not specified, Git fetches all branches and tags.

Example Usages of git fetch:

  • Fetching All Changes from the Default Remote:

    git fetch
    

    This command fetches all updates from the default remote repository (origin). After running this, you can view the commit history of the remote master branch using:

    git log origin/master
    
  • Fetching a Specific Branch from a Remote:

    git fetch origin feature-branch
    

    This command fetches updates from the feature-branch in the origin remote repository. After fetching, you can view the commit history of the remote feature-branch using:

    git log origin/feature-branch
    

git pull

The git pull command is used to fetch changes from a remote repository and automatically merge them into your current local branch. It essentially combines the functionalities of git fetch and git merge.

Basic Command Syntax:

git pull [<options>] [<repository> [<refspec>...]]

Common git pull Flags:

  • --rebase: Performs a rebase of the current branch on top of the fetched branch instead of creating a merge commit. This is recommended if you want to maintain a linear commit history.
  • --no-rebase: Cancels any rebase behavior and performs a standard merge instead.
  • --no-commit: Prevents Git from creating an automatic commit after the merge. This allows you to make additional changes before committing.
  • --ff-only: Only performs the merge if it can be done with a fast-forward. If not, the pull is aborted.
  • --no-ff: Forces a merge commit even if a fast-forward is possible.

Example Usages of git pull:

  • Standard Pull with Automatic Merge:

    git pull
    

    This command fetches changes from the remote repository and merges them into the current branch.

  • Pull with Rebase:

    git pull --rebase
    

    This command fetches changes and rebases the current branch on top of the fetched changes, maintaining a linear history.

  • Pull without Automatic Commit:

    git pull --no-commit
    

    This command fetches and merges changes but does not create an automatic commit, allowing you to review and modify the changes before committing.

  • Pull with Fast-Forward Only:

    git pull --ff-only
    

    This command performs the pull only if it can be done with a fast-forward merge. If not, the pull is aborted to prevent a merge commit.

  • Pull with No Fast-Forward:

    git pull --no-ff
    

    This command forces a merge commit even if a fast-forward merge is possible, ensuring that the branch history remains intact.


git push

The git push command is used to send your local repository's changes to a remote repository. This updates the remote repository with your local commits, making them available to other collaborators.

Command Syntax:

git push <remote> <branch>
  • <remote>: The name of the remote repository you want to push to (e.g., origin).
  • <branch>: The name of the branch you want to push to the remote repository.

Example Usages of git push:

  • Pushing Changes to the main Branch on origin:

    git push origin main
    

    This command pushes the commits from your local main branch to the main branch in the remote repository named origin.

Additional git push Flags:

  • -u or --set-upstream: Sets the upstream tracking relationship for the branch, allowing you to use git push and git pull without specifying the remote and branch names in the future.
  • -f or --force: Forces Git to overwrite the remote branch with your local branch, even if it results in data loss. Use this with caution.
  • -n or --dry-run: Simulates the push operation without actually sending any changes to the remote repository. This is useful for testing what the push would do.
  • -v or --verbose: Provides detailed information about the push process.

Example Usage with Flags:

  • Pushing with Upstream Tracking:

    git push -u origin main
    

    This command pushes the main branch to the origin remote repository and sets it to track the remote main branch. Future pushes and pulls can be done without specifying origin and main.

  • Force Pushing to Overwrite Remote Branch:

    git push -f origin main
    

    This command forcefully pushes the main branch to origin, overwriting the remote main branch with your local changes. Use this option with caution as it can lead to loss of data on the remote repository.

  • Dry Run Push to Test Changes:

    git push -n origin main
    

    This command simulates pushing the main branch to origin without making any actual changes, allowing you to see what would happen during the push.

  • Verbose Push for Detailed Output:

    git push -v origin main
    

    This command provides detailed information about the push process, which can be helpful for debugging or understanding what Git is doing during the push.

The git push command is essential for sharing your work with others and updating the remote repository with your latest changes. Using the appropriate flags allows you to control how your changes are pushed and how they interact with the remote repository's history.


Working with Files

git status

The git status command is used to obtain information about the current state of your Git working environment. It displays which files have been modified, which ones have been staged (added to the index), and which are ready to be committed. Additionally, the git status command provides information about the current branch and other useful details.

Command Syntax:

git status [-s] [--long] [--branch] [--porcelain] [--ignore-submodules[=<when>]]

Common Flags:

  • -s or --short: Displays a concise summary of the file statuses, similar to the output of git diff --shortstat.
  • --long: Shows the full status, including detailed information about the latest commit for each file.
  • --branch: Displays information about the current branch and its status relative to the remote branch.
  • --porcelain: Outputs the status in a machine-readable format, which is useful for automation scripts.
  • --ignore-submodules: Allows you to ignore changes in submodules.

Example Usage of git status:

$ git status

Example Output:

On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)

        modified:   README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)

        modified:   index.html

no changes added to commit (use "git add" and/or "git commit -a")

This output indicates that you are on the main branch, your local branch is ahead of origin/main by one commit, and there are changes in the files README.md (staged for commit) and index.html (not staged). To stage index.html, you would use the command git add index.html.


git rm

The git rm command is used to remove files from both the working directory and the Git index (staging area). This is an efficient way to delete a file from tracking and prepare the deletion for the next commit. After executing this command, the files will be removed from your working directory and will no longer be tracked by Git.

Command Syntax:

git rm <file>...

Common Options:

  • --cached: Removes the files from the index but keeps them in your working directory. This is useful if you want to stop tracking a file (for example, adding it to .gitignore) without deleting it from your filesystem.
  • -f or --force: Forces the removal of files, even if they have changes that haven't been committed or are already staged. Use this option with caution to avoid losing important changes.

Example Usage of git rm:

  • Removing a File from Both the Working Directory and the Index:

    $ git rm example.txt
    

    This command deletes example.txt from your working directory and removes it from the Git index, preparing the deletion for the next commit.

  • Removing a File Only from the Index (Keeping It in the Working Directory):

    $ git rm --cached config.ini
    

    This command stops tracking config.ini in Git but leaves the file intact in your working directory.

After executing git rm, the changes are ready to be committed, meaning you can record the file deletions in the repository's history using git commit.

Using the git rm command ensures a clean and managed way to delete files from your repository, allowing you to easily track and commit such changes.


git mv

The git mv command is used to move or rename files or directories within a Git repository. This action is automatically staged by Git, simplifying the process of preparing changes for the next commit. Unlike manually renaming a file and then using git add for the new file and git rm for the old one, git mv handles both operations simultaneously.

Command Syntax:

git mv <source> <destination>
  • <source>: The current name of the file or directory.
  • <destination>: The new name or the path to the directory where the file or directory should be moved.

Example Usages of git mv:

  • Renaming a File:

    $ git mv oldName.txt newName.txt
    

    This command renames oldName.txt to newName.txt and automatically stages the change for the next commit.

  • Moving a File to a Directory:

    $ git mv example.txt directory/
    

    This command moves example.txt into the directory/ folder and stages the change.

After executing git mv, the changes are ready to be committed. You can use git commit to record the file renaming or moving in your repository's history.

Using the git mv command provides an efficient and straightforward way to manage files and directories within your repository, automatically tracking these changes in the version control system.


Removing Accidentally Added Files from Commit History

Sometimes, large files or entire directories—such as trained models exceeding 100 MB—may be accidentally added to your commit history. In such cases, the git-filter-repo tool is invaluable for efficiently cleaning your repository's history.

Installing git-filter-repo

Before using the tool, ensure that it is installed. You can install git-filter-repo using pip as follows:

python3 -m pip install --user git-filter-repo

Cleaning Commit History

To remove a specific directory (for example, distil_bert/) along with its contents from the commit history, use the following command:

git filter-repo --invert-paths --path distil_bert/ --force

If you need to remove a specific file, specify its full path:

git filter-repo --invert-paths --path 'predict/src/tasks/distil_bert/model.safetensors' --force

Restoring Connection to the Remote Repository

After applying git-filter-repo, the connection between your local and remote repositories might be lost. To check the current remote repository settings, run:

git remote -v

This command displays the URLs for fetching and pushing. If the connection is broken, you can re-add the remote repository:

git remote add origin https://github.com/username/repo-name.git

Pushing Changes

Create a new commit to record the removals:

git add .
git commit -m "Remove large files"

To forcefully push the changes for the current branch to the remote repository, use:

git push origin --force HEAD

To forcefully update all branches, push changes to all remote branches:

git push origin --force --all

Important Reminder

Force-pushing changes to main branches can result in the loss of important data for your team. Always coordinate such actions with your colleagues to avoid conflicts and data loss.

ChatGPT
Eva
💫 Eva assistant