Как удалить папку в gitlab
Перейти к содержимому

Как удалить папку в gitlab

  • автор:

Как удалить директорию в Git?

Если вы случайно закоммитили ненужный файл или папку в git-репозиторий и уже сделали push, то чтобы удалить все следы этого файла или папки в том числе и из истории, достаточно выполнить команду:

git filter-branch —tree-filter «rm -rf PATH» HEAD

где PATH — это относительный путь до файла или папки.
После этого выполните (чтобы перезаписать историю изменений):

git push origin master —force

  • Facebook
  • Вконтакте
  • Twitter

В моем случае при вводе команды
git filter-branch —tree-filter «rm -rf PATH» HEAD
удаляется каталог PATH с жесткого диска.

Чтобы этого избежать перед этой командой я выполнил
git filter-branch —force

Как удалить каталог из репозитория git?

У меня есть 2 каталога в моем репозитории GitHub. Я хотел бы удалить один из них. Как я могу сделать это без удаления и повторного создания всего репозитория?

12 ответов:

удалить каталог из git и local

вы можете проверить «мастер» с обоих каталогов;

удалить каталог из git, но не локальный

как уже упоминалось в комментариях, то, что вы обычно хотите сделать, это удалить этот каталог из git, но не удалить его полностью из файловой системы (local)

в этом случае:

чтобы удалить папку / каталог только из репозитория git, а не из локального попробуйте 3 простых команды.

шаги для удаления каталога

шаги, чтобы игнорировать эту папку в следующей совершает

чтобы игнорировать эту папку из следующих коммитов, сделайте один файл в корне с именем .gitignore и поместите это имя папки в него. Вы можете поставить столько, сколько вы хочу!—8—>

.gitignore файл будет выглядеть так

remove directory

Если по какой-то причине то, что сказал кармаказе, не работает, вы можете попробовать удалить каталог, который вы хотите удалить (через браузер файловой системы), выдав команду
git add -A
а потом
git commit -m ‘deleting directory’
а потом
git push origin master .

вы можете попробовать это: git rm -rf <directory_name>

Это заставит удалить каталог.

если вы удалите файлы в каталоге (с git rm Как объясняют другие ответы), то каталог больше не существует, насколько это касается git. Вы не можете зафиксировать пустой каталог и не можете его удалить.

это не похоже на subversion, где вы должны явно svn rm emptyfolder/ и кстати, почему man страница для git описывает себя как «глупый контент-трекер»

ответ на вопрос » как добавить пустой каталог в git репозиторий» ссылки FAQ по этой теме:

В настоящее время дизайн индекса git (промежуточная область) разрешает только файлы перечислитесь, и никто не достаточно компетентен чтобы внести изменения, чтобы разрешить пустой каталоги заботился достаточно о эту ситуацию исправить.

каталоги добавляются автоматически при добавлении файлов внутри них. Что есть каталоги не должны быть добавлены в репозиторий, а не гусеничный самостоятельно.

вы можете сказать:» git add <dir> » и добавлю туда файлы.

Если вам действительно нужен каталог существовать в полку, вы должны создать файлы в ней. .пример хорошо работает для эта цель; вы можете оставить его пустым, или заполнять имена файлов ожидал увидеть в каталоге.

перейдите в каталог git и введите следующую команду: rm-rf Имя Директории>

после удаления каталога зафиксируйте изменения с помощью: git commit-m «ваше сообщение о фиксации»

затем просто нажмите изменения в удаленном каталоге GIT: git push origin филиала>

Я обычно использую git add —all для удаления файлов / папок из удаленных репозиториев

master может быть заменен на любой другой ветке репозитория.

вы можете удалить папку локально, а затем нажать, как показано ниже:

вы можете использовать Attlasian Source Tree (Windows) (https://www.atlassian.com/software/sourcetree/overview). Просто выберите файлы из дерева и нажмите кнопку «Удалить» в верхней части. Файлы будут удалены из локального репозитория и локальной базы данных git. Затем зафиксируйте, затем нажмите.

один из моих коллег предложил BFG Repo-Cleaner который я считаю мощным. Это не только удалить ненужные данные, но и очистить репозиторий от любой связанной информации фиксации.

  1. git init
  2. git config user.name «кто-то»
  3. git config user.электронная почта «[email protected]»
  4. git rm-r
  5. git commit-m «удаление dir»
  6. git push origin master

добавить новый каталог:

но теперь Git не знает об этом новом каталоге, потому что Git отслеживает файлы, а не каталоги Каталог

Git не будет знать об изменениях, которые мы сделали, поэтому мы добавляем hidden .keep файл, чтобы Git знал об этом новом изменении.

теперь, если вы нажмете git status Git будет в курсе изменений.

и если вы хотите удалить каталог, вы должны использовать это команда.

и если вы проверили с помощью git status , вы увидите, что каталог был удален.

10 ways to delete file or directory effortlessly in GIT

git delete a file or directory by running the clean command with various options. For example, use the -f option to delete a file only.

Use the -i option

to delete the file interactively

combine -f and -d options to delete files and directories.

Sometimes you need to git delete file or directory depending on whether it is ignored or not. To delete ignored files only, use capital -X

For both ignored and unignored files, use small -x .

Apart from the git commands, you can use Unix commands such as

to delete a file or folder from any level of the git workflow.

2. git delete file or directory from a repository

3. git delete file or directory from the history

You can delete a committed file by doing a hard reset on the commit’s HEAD or commit id.

Better yet, you can use the filter-branch command to delete the file with all its commits.

What we mean by filesystem and repository

Technically, a filesystem and a repository mean the same thing. However, git users refer to different things when using the terms.

For instance, it is a convention amongst git users to collectively refer to untracked or tracked files and folders as a filesystem.

The difference between filesystem and directory arises upon staging a file. Then, the staged files or folders become a snapshot of the entity (filesystem).

Simply put, the repository references staged files, whereas the filesystem is the entire body containing the directories and files: tracked and untracked.

The files resume a riskier level within the workflow on git delete file or directory from the filesystem or repository.

For instance, a committed file will likely end up in the index, working tree or disappear from the workflow. Also, most indexed files end up in the working directory when you git delete file or directory.

Let us set up a lab and practically see how to git delete file or directory works.

Lab set up to explore git delete file or directory

I am creating a repository on GitHub called delete_file with a README.md file then copying its URL

remote to practice git delete file or directory

Clone and cd into it.

10 ways to delete file or directory effortlessly in GIT

Next, let us create three files and two directories with two files each.

Check all files and folders, hidden and unhidden.

10 ways to delete file or directory effortlessly in GIT

Example

1: Delete file or directory using git rm command only

Git rm command deletes a tracked file or folder from the filesystem.

Let us stage and commit all files before applying git rm on them.

We can now delete file1 as follows

First, check the status.

Then delete the file.

And recheck the status.

Git tells us file1 got removed from the filesystem and deleted from the repository.

git delete file or directory using git rm

Let us record the deletion in the history before proceeding with another command.

And check the status. The file no longer exists among the listed ones.

10 ways to delete file or directory effortlessly in GIT

Example

2: Recursively delete file or directory using git rm command

Adding the recursive option deletes a file similarly to the rm command without an option. The difference between the recursive option and the former command is that we can use the recursive option to delete a directory.

Let us use it to delete file2 , repeating the procedures of example

Then submit the message to the history

And check tracked files.

10 ways to delete file or directory effortlessly in GIT

Example

3: Delete file or directory using git rm with cached option

The cached option deletes a file from the index.

Let us use it to untrack dir1_file.txt file.

First, check the status.

Then apply the command

And recheck the status.

The file is unavailable!

We can also recursively delete an entire directory from the index.

Rechecking the status

confirms that the entire dir1 got deleted from the index. But we can trace its remnants in the working directory.

10 ways to delete file or directory effortlessly in GIT

Lastly, let us record the deletions in history.

Example

4: Delete file or directory with the git clean and -f option

Git clean with the -f option comes into play when deleting an untracked file after unstaging the directories with git rm with the cached command.

Let us apply it as follows.

10 ways to delete file or directory effortlessly in GIT

Example

5: Interactively delete a file

Similarly, we can interactively delete unstaged files using the -i flag as follows.

Example

6: Delete untracked file or directory using the clean command

Git clean with the -f and -d options delete an untracked directory. We can apply it as follows.

Example

7: Delete ignored files using git clean command with -fX options

git clean with -f and -X options delete ignored files. Let us test it by creating a .gitinore file with two more files.

Reference the two files in the .gitinore file.

Press Ctrl + d to exit the command, then cat the file.

Our two files are referenced in .gitignore . We can delete the ignored files as follows.

10 ways to delete file or directory effortlessly in GIT

Example

8: Delete ignored and unignored files using git clean command with -fx options

We can delete both ignored and unignored files by following these steps.

Return the files we deleted in example

7 and an extra one.

Then delete all the new files.

10 ways to delete file or directory effortlessly in GIT

Example

9: git delete file or directory through a hard reset

Doing a hard reset on a commit deletes the commit and the affected file.

Let us delete all the files introduced after the initial commit. First, log the history to know the number of commits after the target one.

Let us hard reset the four commits from the HEAD.

Check the files and folders.

They are all gone, except the README.md file

10 ways to delete file or directory effortlessly in GIT

Example

10: git delete file or directory using the filter-branch command

Unlike git rm and git reset hard that leave file traces in the branch, tag or reflog, git filter-branch enables us to git delete file or directory without leaving any history behind.

Let us create a file, stage, and commit it before applying the git filter-branch command.

Delete the file and its history as follows.

10 ways to delete file or directory effortlessly in GIT

Conclusion

Git delete file or directory can be comfortable when you apply a suitable command in the working directory, index, history. Now that you know the best command per situation, go ahead and enjoy your version tracking with git.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

How do I remove a directory from a Git repository?

How can I delete a single directory containing files from a Git repository?

John Smith's user avatar

16 Answers 16

Remove directory from Git and local

Checkout ‘master’ with both directories:

Remove directory from Git but NOT local

To remove this directory from Git, but not delete it entirely from the filesystem (local):

John Smith's user avatar

To remove folder/directory only from git repository and not from the local try 3 simple commands.

Steps to remove directory

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root folder (main project directory where the git is initialized) named .gitignore and put that folder name into it. You can ignore as many files/folders as you want

.gitignore file will look like this

remove directory

If, for some reason, what karmakaze said doesn’t work, you could try deleting the directory you want using or with your file system browser (ex. In Windows File Explorer). After deleting the directory, issuing the command:
git add -A
and then
git commit -m ‘deleting directory’
and then
git push origin master .

sophros's user avatar

I already had committed the folder before and want to remove the directory in the history as well.

I did the following:

Add folder to .gitignore :

Remove from all commits:

remove the refs from the old commits:

Ensure all old refs are fully removed

Perform a garbage collection

push you changes to the online repository:

You are done here.

But you can to the following to push all the changes to all branches with: But be careful with this command!

After that the folder was removed from git, but was not deleted from local disk.

You can try this: git rm -rf <directory_name>

It will force delete the directory.

Breen ho's user avatar

If you remove the files in the directory (with git rm as the other answers explain), then the directory no longer exists as far as git is concerned. You cannot commit an empty directory, nor can you remove one.

This is unlike subversion where you have to explicitly svn rm emptyfolder/ , and is incidentally why the man page for git describes itself as «the stupid content tracker»

Currently the design of the git index (staging area) only permits files to be listed, and nobody competent enough to make the change to allow empty directories has cared enough about this situation to remedy it.

Directories are added automatically when adding files inside them. That is, directories never have to be added to the repository, and are not tracked on their own.

You can say » git add <dir> » and it will add files in there.

If you really need a directory to exist in checkouts you should create a file in it. .gitignore works well for this purpose; you can leave it empty, or fill in the names of files you expect to show up in the directory.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *