git-rm(1) Manual Page
Remove files matching pathspec from the index, or from the working tree and the index. git rm will not remove a file from just your working directory. (There is no option to remove a file only from the working tree and yet keep it in the index; use /bin/rm if you want to do that.) The files being removed have to be identical to the tip of the branch, and no updates to their contents can be staged in the index, though that default behavior can be overridden with the -f option. When —cached is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index. When sparse-checkouts are in use (see git-sparse-checkout(1)), git rm will only remove paths within the sparse-checkout patterns.
OPTIONS
Files to remove. A leading directory name (e.g. dir to remove dir/file1 and dir/file2 ) can be given to remove all files in the directory, and recursively all sub-directories, but this requires the -r option to be explicitly given.
The command removes only the paths that are known to Git.
File globbing matches across directory boundaries. Thus, given two directories d and d2 , there is a difference between using git rm ‘d*’ and git rm ‘d/*’ , as the former will also remove all of directory d2 .
For more details, see the pathspec entry in gitglossary(7).
Override the up-to-date check.
Don’t actually remove any file(s). Instead, just show if they exist in the index and would otherwise be removed by the command.
Allow recursive removal when a leading directory name is given.
This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for command-line options).
Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.
Exit with a zero status even if no files matched.
Allow updating index entries outside of the sparse-checkout cone. Normally, git rm refuses to update index entries whose paths do not fit within the sparse-checkout cone. See git-sparse-checkout(1) for more.
git rm normally outputs one line (in the form of an rm command) for each file removed. This option suppresses that output.
Pathspec is passed in <file> instead of commandline args. If <file> is exactly — then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config(1)). See also —pathspec-file-nul and global —literal-pathspecs .
Only meaningful with —pathspec-from-file . Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
REMOVING FILES THAT HAVE DISAPPEARED FROM THE FILESYSTEM
There is no option for git rm to remove from the index only the paths that have disappeared from the filesystem. However, depending on the use case, there are several ways that can be done.
Using “git commit -a”
If you intend that your next commit should record all modifications of tracked files in the working tree and record all removals of files that have been removed from the working tree with rm (as opposed to git rm ), use git commit -a , as it will automatically notice and record all removals. You can also have a similar effect without committing by using git add -u .
Using “git add -A”
When accepting a new code drop for a vendor branch, you probably want to record both the removal of paths and additions of new paths as well as modifications of existing paths.
Typically you would first remove all tracked files from the working tree using this command:
and then untar the new code in the working tree. Alternately you could rsync the changes into the working tree.
After that, the easiest way to record all removals, additions, and modifications in the working tree is:
Other ways
If all you really want to do is to remove from the index the files that are no longer present in the working tree (perhaps because your working tree is dirty so that you cannot use git commit -a ), use the following command:
SUBMODULES
Only submodules using a gitfile (which means they were cloned with a Git version 1.7.8 or newer) will be removed from the work tree, as their repository lives inside the .git directory of the superproject. If a submodule (or one of those nested inside it) still uses a .git directory, git rm will move the submodules git directory into the superprojects git directory to protect the submodule’s history. If it exists the submodule.<name> section in the gitmodules(5) file will also be removed and that file will be staged (unless —cached or -n are used).
A submodule is considered up to date when the HEAD is the same as recorded in the index, no tracked files are modified and no untracked files that aren’t ignored are present in the submodules work tree. Ignored files are deemed expendable and won’t stop a submodule’s work tree from being removed.
If you only want to remove the local checkout of a submodule from your work tree without committing the removal, use git-submodule(1) deinit instead. Also see gitsubmodules(7) for details on submodule removal.
EXAMPLES
Removes all *.txt files from the index that are under the Documentation directory and any of its subdirectories.
Note that the asterisk * is quoted from the shell in this example; this lets Git, and not the shell, expand the pathnames of files and subdirectories under the Documentation/ directory.
git rm
В начале использования Git часто возникает вопрос: «Как заставить Git больше не отслеживать какой-либо файл или несколько файлов?» Чтобы удалить файлы из репозитория Git, можно воспользоваться командой git rm . Ее действие противоположно действию команды git add .
Обзор команды git rm
Команда git rm позволяет удалять отдельные файлы или группы файлов. Основное назначение git rm — удаление отслеживаемых файлов из раздела проиндексированных файлов Git. Кроме того, с помощью git rm можно удалить файлы одновременно из раздела проиндексированных файлов и рабочего каталога. Удалить с ее помощью файл только из рабочего каталога нельзя. Файлы, в отношении которых выполняется команда, должны быть идентичны файлам в текущем указателе HEAD . В случае расхождений между версией файла из указателя HEAD и версией из раздела проиндексированных файлов или рабочего дерева Git заблокирует удаление. Такая блокировка является механизмом безопасности, который предотвращает удаление изменений в процессе их внесения.
Обратите внимание, что git rm не удаляет ветки. Подробнее об использовании веток Git см. здесь.
Использование
Указывает файлы, подлежащие удалению. Можно указать один файл, несколько файлов через пробел ( file1 file2 file3 ) или шаблон подстановки (
Параметр -f применяется для отключения проверки безопасности, с помощью которой Git обеспечивает соответствие файлов в указателе HEAD текущему содержимому раздела проиндексированных файлов и рабочего каталога.
Параметр dry run является защитным механизмом. Он позволяет выполнить пробный запуск команды git rm без удаления файлов. В выходных данных отображаются файлы, которые должны были быть удалены.
Параметр -r — это сокращение от слова recursive. При выполнении команды git rm в рекурсивном режиме она удаляет не только каталог назначения, но и все содержимое его вложенных каталогов.
Параметр разделителя позволяет явным образом отличить список имен файлов от аргументов, передаваемых команде git rm . Разделитель полезен, когда какие-либо из файлов имеют имена, аналогичные параметрам команды.
Параметр cached указывает, что должны быть удалены только файлы, находящиеся в разделе проиндексированных файлов. Файлы в рабочем каталоге при этом остаются нетронутыми.
Этот параметр заставляет команду завершиться со статусом sigterm, равным 0, даже если файлы, указанные для удаления, не найдены. Sigterm — это код состояния в Unix. Код 0 указывает на успешный вызов команды. Параметр —ignore-unmatch может быть полезен, если команда git rm используется в составе скрипта оболочки, который должен обеспечивать корректную обработку отказа.
Параметр quiet скрывает вывод команды git rm . Как правило, команда выводит по одной строке на каждый удаленный файл.
Отмена изменений, внесенных командой git rm
Изменения, вносимые при выполнении команды git rm , не являются окончательными. Эта команда обновляет раздел проиндексированных файлов и рабочий каталог. Изменения не сохранятся, пока не будет создан новый коммит и они не будут добавлены в историю коммитов. Так что изменения, внесенные командой git rm, можно «отменить» с помощью стандартных команд Git.
Команда git reset восстановит раздел индексированных файлов и рабочий каталог до коммита HEAD . В результате изменения, внесенные командой git rm , будут отменены.
Такого же результата можно добиться с помощью команды git checkout: она восстановит последнюю версию файла из указателя HEAD .
Если после выполнения git rm был создан новый коммит, из-за которого удаление сохранилось, можно воспользоваться командой git reflog , чтобы найти ссылку, предшествующую выполнению git rm . Подробнее об использовании git reflog см. здесь.
Пояснения
Аргумент , переданный команде, может содержать точные пути, шаблоны поиска файлов или точные имена каталогов. При выполнении команды удаляются только пути, зафиксированные в репозитории Git посредством коммитов.
В шаблонах поиска файлов можно задавать имена каталогов. При использовании шаблонов поиска следует быть внимательным. Рассмотрим примеры: directory/* и directory* . Использование первого шаблона приведет к удалению всех файлов в каталоге directory/ , тогда как второй вызовет удаление всех каталогов, имя которых начинается на directory — например, directory1 , directory2 , directory_whatever и т. д., что может быть нежелательным.
Область действия команды git rm
Действие команды git rm распространяется только на текущую ветку. Удаление выполняется только в деревьях рабочего каталога и раздела проиндексированных файлов. Удаление файла не сохраняется в истории репозитория до тех пор, пока не создан новый коммит.
Почему следует использовать git rm, а не rm
Репозиторий Git обнаруживает выполнение стандартной команды оболочки rm для отслеживаемого им файла и соответствующим образом обновляет рабочий каталог. Но раздел проиндексированных файлов не обновляется. Чтобы внести в него изменения, для удаленных путей к файлам необходимо дополнительно выполнить команду git add . Команда git rm уменьшает количество действий, поскольку обновляет при удалении и рабочий каталог, и раздел проиндексированных файлов.
Примеры
В данном примере шаблон поиска файлов используется для удаления всех файлов *.txt в каталоге Documentation и всех его подкаталогах.
Обратите внимание, что символ звездочки * здесь экранируется символами косой черты. Это сделано, чтобы оболочка не расширяла шаблон. В таком варианте он включает только пути к файлам и подкаталогам, находящимся в каталоге Documentation/ .
В этом примере команда выполняется с параметром force для всех файлов, соответствующих шаблону подстановки git-*.sh . Параметр force явным образом удаляет целевые файлы из рабочего каталога и раздела проиндексированных файлов.
Удаление файлов, которых уже нет в файловой системе
В разделе «Почему следует использовать git rm , а не rm » говорилось о том, что команда git rm предусмотрена для удобства: она сочетает функции стандартной команды оболочки rm и команды git add , позволяя удалить файл из рабочего каталога и раздела проиндексированных файлов. Если удалить несколько файлов с помощью стандартной команды оболочки rm , состояние репозитория может стать проблематичным.
Если требуется записать все явным образом удаленные файлы в следующий коммит, можно выполнить команду git commit -a . Она внесет все события удаления в раздел проиндексированных файлов для подготовки к следующему коммиту.
Если же стоит задача безвозвратно удалить файлы, удаленные с помощью команды оболочки rm , нужно воспользоваться следующей командой:
Эта команда создаст список удаленных файлов из рабочего каталога и передаст его команде git rm —cached , которая обновит раздел проиндексированных файлов.
Команда git rm: заключение
Команда git rm выполняет действия над двумя главными деревьями управления внутренним состоянием Git: рабочим каталогом и разделом проиндексированных файлов. Команда git rm позволяет удалять файлы из репозитория Git. Это удобный инструмент, объединяющий функции стандартной команды оболочки rm и команды git add : сначала git rm удаляет целевой объект из файловой системы, а затем добавляет событие удаления в раздел проиндексированных файлов. Эта команда — одна из многих, которые можно использовать для отмены изменений в Git.
Как удалить файл через git bash
- English
- Français
- Português (Brasil)
Setup and Config
Getting and Creating Projects
Basic Snapshotting
Branching and Merging
Sharing and Updating Projects
Inspection and Comparison
Patching
Debugging
External Systems
Server Admin
Guides
Administration
Plumbing Commands
- 2.34.1 → 2.39.2 no changes
- 2.34.0 11/15/21
- 2.32.1 → 2.33.7 no changes
- 2.32.0 06/06/21
- 2.26.1 → 2.31.7 no changes
- 2.26.0 03/22/20
Check your version of git by running
git-rm — Remove files from the working tree and from the index
SYNOPSIS
DESCRIPTION
Remove files matching pathspec from the index, or from the working tree and the index. git rm will not remove a file from just your working directory. (There is no option to remove a file only from the working tree and yet keep it in the index; use /bin/rm if you want to do that.) The files being removed have to be identical to the tip of the branch, and no updates to their contents can be staged in the index, though that default behavior can be overridden with the -f option. When —cached is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index. When sparse-checkouts are in use (see git-sparse-checkout[1]), git rm will only remove paths within the sparse-checkout patterns.
OPTIONS
Files to remove. A leading directory name (e.g. dir to remove dir/file1 and dir/file2 ) can be given to remove all files in the directory, and recursively all sub-directories, but this requires the -r option to be explicitly given.
The command removes only the paths that are known to Git.
File globbing matches across directory boundaries. Thus, given two directories d and d2 , there is a difference between using git rm ‘d*’ and git rm ‘d/*’ , as the former will also remove all of directory d2 .
For more details, see the pathspec entry in gitglossary[7].
Override the up-to-date check.
Don’t actually remove any file(s). Instead, just show if they exist in the index and would otherwise be removed by the command.
Allow recursive removal when a leading directory name is given.
This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for command-line options).
Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.
Exit with a zero status even if no files matched.
Allow updating index entries outside of the sparse-checkout cone. Normally, git rm refuses to update index entries whose paths do not fit within the sparse-checkout cone. See git-sparse-checkout[1] for more.
git rm normally outputs one line (in the form of an rm command) for each file removed. This option suppresses that output.
Pathspec is passed in <file> instead of commandline args. If <file> is exactly — then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config[1]). See also —pathspec-file-nul and global —literal-pathspecs .
Only meaningful with —pathspec-from-file . Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
REMOVING FILES THAT HAVE DISAPPEARED FROM THE FILESYSTEM
There is no option for git rm to remove from the index only the paths that have disappeared from the filesystem. However, depending on the use case, there are several ways that can be done.
Using “git commit -a”
If you intend that your next commit should record all modifications of tracked files in the working tree and record all removals of files that have been removed from the working tree with rm (as opposed to git rm ), use git commit -a , as it will automatically notice and record all removals. You can also have a similar effect without committing by using git add -u .
Using “git add -A”
When accepting a new code drop for a vendor branch, you probably want to record both the removal of paths and additions of new paths as well as modifications of existing paths.
Typically you would first remove all tracked files from the working tree using this command:
and then untar the new code in the working tree. Alternately you could rsync the changes into the working tree.
After that, the easiest way to record all removals, additions, and modifications in the working tree is:
Other ways
If all you really want to do is to remove from the index the files that are no longer present in the working tree (perhaps because your working tree is dirty so that you cannot use git commit -a ), use the following command:
SUBMODULES
Only submodules using a gitfile (which means they were cloned with a Git version 1.7.8 or newer) will be removed from the work tree, as their repository lives inside the .git directory of the superproject. If a submodule (or one of those nested inside it) still uses a .git directory, git rm will move the submodules git directory into the superprojects git directory to protect the submodule’s history. If it exists the submodule.<name> section in the gitmodules[5] file will also be removed and that file will be staged (unless —cached or -n are used).
A submodule is considered up to date when the HEAD is the same as recorded in the index, no tracked files are modified and no untracked files that aren’t ignored are present in the submodules work tree. Ignored files are deemed expendable and won’t stop a submodule’s work tree from being removed.
If you only want to remove the local checkout of a submodule from your work tree without committing the removal, use git-submodule[1] deinit instead. Also see gitsubmodules[7] for details on submodule removal.
EXAMPLES
Removes all *.txt files from the index that are under the Documentation directory and any of its subdirectories.
Note that the asterisk * is quoted from the shell in this example; this lets Git, and not the shell, expand the pathnames of files and subdirectories under the Documentation/ directory.
Основные команды bash, git, npm и yarn, а также немного о package.json и semver
Предлагаю вашему вниманию небольшую шпаргалку по основным командам bash, git, npm, yarn, package.json и semver.
Условные обозначения: [dir-name] — означает название директории, | — означает «или».
Рекомендую вводить каждую команду в терминале и внимательно изучать вывод, так вы быстро их запомните и определите, какие команды вам нужны, а какие нет.
Приношу извинения за возможные ошибки и опечатки. Буду рад любым замечаниям и предложениям.
Без дальнейших предисловий.
bash представляет собой инструмент командной строки, позволяющий выполнять некоторые распространенные действия.
Установка: в моем случае bash был установлен вместе с git.
Выход из терминала:
Путь к текущей директории:
Копирование, перемещение и удаление файла:
Вывод в терминал строки:
git представляет собой распределенную систему контроля версий, позволяющую контролировать процесс внесения изменений в проект.
Удаление файлов и директорий:
Просмотр состояния репозитория:
Добавление сообщения (коммита):
Просмотр разницы между коммитами:
Просмотр истории изменений:
Работа с ветками:
Разрешение конфликтов при слиянии:
Сохранение незакоммиченных изменений:
Автозавершение повторных конфликтов:
Пример алиасов (сокращений) для .gitconfig:
npm представляет собой пакетный менеджер, позволяющий устанавливать зависимости проекта.
npm устанавливается вместе с Node.js.
Также вместе с Node.js устанавливается npx, позволяющий запускать исполняемые файлы без установки: npx create-react-app my-app.
Список доступных команд:
Принудительная переустановка зависимостей:
Установка только продакшн-пакетов:
Добавление зависимости для разработки:
Глобальная установка/обновление/удаление пакета:
Определение устаревших пакетов:
Список установленных зависимостей:
Информация о пакете:
Запуск скрипта/выполнение команды:
Удаление дублирующихся пакетов:
Удаление посторонних пакетов:
Обнаружение уязвимостей (угроз безопасности):
Автоматическое исправление уязвимостей:
yarn, как и npm, представляет собой пакетный менеджер, позволяющий устанавливать зависимости проекта.
Команда «yarn dlx» позволяет запускать исполняемые файлы без установки: yarn dlx create-react-app my-app. Для этого yarn необходимо обновить до второй версии: yarn set version berry.
Список доступных команд:
Принудительная переустановка зависимостей:
Установка только продакшн-пакетов:
Добавление зависимости для разработки:
Глобальная установка/обновление/удаление пакета:
Список установленных зависимостей:
Информация о пакете:
Запуск скрипта/выполнение команды:
package.json
- name — название проекта
- version — версия проекта (см. версионирование)
- description — описание проекта (зачем нужен пакет?)
- keywords — ключевые слова (облегчает поиск в реестре npm)
- private — установка значения в true предотвращает случайную публикацию пакета в реестре npm
- main — основная точка входа для функционирования проекта
- repository — ссылка на репозиторий (один из вариантов)
- author — автор проекта (один из вариантов)
- contributors — участники проекта (люди, внесшие вклад в проект)
- dependencies — зависимости проекта (пакеты, без которых приложение не будет работать)
- devDependencies — зависимости для разработки (пакеты, без которых приложение будет работать)
- scripts — команды (выполняемые сценарии, задачи), предназначенные для автоматизации, например, команда «yarn dev» запустит скрипт «nodemon server.js»
Файлы «package-lock.json» и «yarn.lock» содержат более полную информацию об установленных пакетах, чем package.json, например, конкретные версии пакетов вместо диапазона допустимых версий.
Версионирование
Каждый пакет имеет версию, состоящую из трех цифр (например, 1.0.0), где первая цифра — мажорная версия (major), вторая — минорная версия (minor), третья — патчевая версия (патч, patch). Выпуск новой версии называется релизом.
Увеличение каждой из этих цифр согласно правилам семантического версионирования (semver) означает следующее: