Удалить файлы ds store

Обновлено: 03.07.2024

wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 13 человек(а).

Finder ((англ. искатель; произносится «фа́йндер») — системный файловый менеджер операционной системы Apple Mac OS) автоматически размещает файл .DS_Store в каждой папке, которую вы открыли. Файлы .DS_Store создаются в Finder во время его обычного процесса работы. Эти файлы содержат параметры просмотра, позиции иконок, размеры окна Finder, фоны окна, а также многие другие свойствами, но скрытые от глаз пользователя.

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

Для удаления поврежденного файла .DS_Store вы должны использовать приложение Terminal.app. Для этого необходимо войти в Mac OS X в качестве Администратора.
  • Откройте новое окно Finder и перейдите в папку Applications (Приложения) слева. (С другой стороны, когда есть 'Finder' рядом с Apple в левом верхнем углу экрана, выберите меню 'Go' (Перейти) и нажмите 'Applications' (Приложения)).
  • Внутри папки Applications почти в самом низу находится папка 'Utilities' (Утилиты). Откройте эту папку.
  • Найдите и дважды щелкните левой кнопкой мыши приложение 'Terminal', чтобы открыть его.
  • В терминале введите следующее: sudo ls (все строчные символы) и нажмите [Enter] на клавиатуре.
  • Терминал предложит ввести пароль. Используйте пароль учетной записи администратора. Если у вас нет пароля, оставьте это поле пустым. [Примечание: В целях безопасности, в отличие от ОС Windows, Mac OS X не «проявит» никаких признаков того, что вы набираете пароль. Просто вводите его нормально, хотя ничего не отображается].

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

  • Чтобы перевести то, что вы делаете в Finder, в письменный вид, начинайте с нажатия 'Macintosh HD' на рабочем столе. Это превратится в символ '/'. Нажмите следующую папку. После имени будет следовать '/' , поэтому введите другой символ '/' перед именами других папок. Например, если папка, с которой у вас возникли проблемы, является 'Macintosh HD' -> 'Applications', путь к этой папке будет: '/Applications'. Если проблемная папка - 'Utilities' внутри 'Applications', то путь будет: '/Applications/Utilities'.
  • Введите cd/path (например: cd /Applications), затем нажмите клавишу Enter.
  • Введите cd в Терминале с последующим пробелом.
  • Найдите папку с проблемой, но не открывайте ее. Перетащите ее значок в Терминал. Смотрите, как завершится процесс создания пути для вас. Нажмите клавишу Enter.

Теперь вы можете удалить папку .DS_Store и все ее содержимое с помощью одной очень мощной команды: 'rm' (Remove или Удалить) плюс параметр '-f' - удаляет все файлы и папки, содержащиеся в target name. ВВОДИТЕ ПРАВИЛЬНО эту команду.

Теперь вы сможете перейти к папке в Finder и эта проблема должна быть исправлена.

Повреждение .DS_Store файлов может препятствовать правильной синхронизации OneDrive. Удаление поврежденных файлов может помочь восстановить нормальную операцию синхронизации.

При удалении поврежденных файлов в качестве средства поиска Mac данные не теряются создание.DS_Store файлов для хранения параметров просмотра, таких как расположение значков, размер окна Finder и фоновые рисунки окон.

Чтобы удалить поврежденный файл .DS_Store, необходимо использовать Terminal. app.

Примечание: Вы должны войти в macOS как администратор.

Откройте новое окно Finder и перейдите в папку приложения в левой части экрана.

Откройте папку Служебные программы, а затем дважды щелкните приложение терминала .

Предоставьте себе разрешения суперпользователя (root) в терминале, чтобы можно было использовать команды для удаления .DS_Store файлов.

В окне терминала введите sudo ls затем нажмите клавишу Ввод на клавиатуре.

Когда терминал запросит пароль, введите пароль своей учетной записи администратора. Если у вас нет пароля, оставьте это поле пустым.

Примечание: В целях обеспечения безопасности macOS не будет показывать ни один знак, на который вы вводите пароль. Просто введите текст в обычном режиме, даже если ничего не отображается.

Перейдите к папке, которая не синхронизируется должным образом.

В поле терминал введите cd , за которым следует пробел.

Найдите папку с проблемой, но не открывайте ее. Вместо этого перетащите его значок в терминал и проследите за тем, как вы закончите путь, и нажмите клавишу return.

Удалите папку .DS_Store и все ее содержимое.

Внимание: Убедитесь, что удаляется нужная папка.

Введите rm -f .DS_Store и нажмите клавишу return.

Дополнительные сведения

Значок "Обратиться в службу поддержки"

Чтобы получить техническую поддержку, Обратитесь в службу поддержки Майкрософт, введите свою проблему и выберите Техническая поддержка. Если вам по-прежнему нужна помощь, выберитеОбратитесь в службу поддержки, чтобы получить наилучший вариант поддержки.

Эмблема для работы или учебного заведения

Примечание: Эта страница переведена автоматически, поэтому ее текст может содержать неточности и грамматические ошибки. Для нас важно, чтобы эта статья была вам полезна. Была ли информация полезной? Для удобства также приводим ссылку на оригинал (на английском языке).

отключить создание .DS_STORE

Наша любимая macOS при обращении к сетевым дискам или флешкам оставляет после себя скрытые файлы .DS_Store, .fseventsd, .Spotlight-V100, .TemporaryItems, .Trashes и файлы с префиксом «._».

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

Что такое .DS_Store, .fseventsd, .Spotlight-V100, TemporaryItems и .Trashes?

Попробую объяснить что это такое и откуда берется. Если совсем кратко, то эти скрытые файлы и папки выполняют вспомогательную функцию файловой системы macOS — запоминают размеры иконок, ведут журналы событий, содержат индексы поиска и прочие «плюшки». Остановимся чуть подробнее на каждом:

  • .DS_Store — отвечает за хранение настроек вида папок (размер пиктограмм и сетки, вид, фоновый рисунок и так далее. Удалив этот файл, все настройки вида придут к настройкам по-умолчанию.
  • Файлы с префиксом «._». Файловая система macOS использует оригинальную систему хранения данных: сам файл плюс ресурсы, которыми можно его сопроводить (добавить пиктограмму, цветную этикетку, комментарий Spotlight). У других файловых систем (FAT, NTFS, UFS, SMB, NFS) такой функции нет и, дабы не терять эти данные на внешних или сетевых дисках, Apple придумала механизм под названием «Apple Double», создавая для этих целей второй файл с префиксом ._. В общем, файлы с префиксом ._ на сетевых ресурсах и флешках можно смело удалять, никакой полезной нагрузки они там не несут.
  • .fseventsd — журнал событий файловой системы, содержит данные о создание файлов и каталогов, модификации, удалении. На несистемных томах можно обойтись и без него.
  • .Spotlight-V100 — база индексации системы поиска Spotlight, пожалуй самый объемный из скрытых системных каталогов. Располагается в корне каждого раздела диска. Удаление приводит к повторному переиндексированию.
  • .TemporaryItems — служит для хранения временных объектов (по аналогии с temp в Windows). Удаление может негативно сказаться на работе программ, которые её используют.
  • .Trashes — используется для временного хранения удалённых файлов. Удаление данной папки равносильно очистке корзины (не рекомендуется удалять на системных разделах).

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

Как избавиться от создания файлов .DS_Store, .Spotlight-V100, .TemporaryItems и .Trashes на сетевых дисках?

Штатных настроек по отключению файлов типа .DS_Store на сетевых дисках в macOS не предусмотрено, хотя способ избавления от некоторых файлов и папок на SMB ресурсах всё-таки есть. Для этого в терминале нужно выполнить команду:

Правда тут есть одно "но". Данная настройка распространяется только на ту учетную запись, под которой выполнялась команда. Если требуется применить её ко всей системе, необходимо скопировать файл com.apple.desktopservices.plist из локальной библиотеки настроек в глобальную и переназначить права доступа:

Восстановить настройки можно командой:

Теперь можно рекурсивно очистить подключенный сетевой ресурс (со всеми подкаталогами) от файлов .DS_Store, .Spotlight-V100 и прочих, описанных ранее. Предполагается, что ресурс уже смонтирован в каталоге /Volumes.

Для этого в терминале выполняем команду:

Запрет создания файлов .DS_Store средствами файлого сервера

Настраивать каждый компьютер с macOS в сети подобным образом, удовольствие весьма сомнительное. Предпочитаю решать проблему глобально, непосредственно на самом файловом сервере. Большинство сетевых накопителей управляются Linux или FreeBSD, предоставляя общие ресурсы по SMB-протоколу (на самом деле можно настроить и AFP, NFS, FTP).

Samba-сервер позволяет запретить создание ненужных файлов и папок c помощью директивы veto files. Она может быть установлена как глобально, так и отдельно для каждого расшаренного сетевого каталога. Пример конфига smb.conf:

Чтобы обеспечить возможность контроля за содержимым файлового сервера на Windows, нам необходимо установить сам «Файловый сервер» и службу «Диспетчер ресурсов файлового сервера». После чего можно настроить запрет сохранения определенных типов файлов по маске в разделе «Управление блокировкой файлов – Фильтры блокировки».

Яндекс.Дзен и узнавайте первыми о новых материалах, опубликованных на сайте.

Если считаете статью полезной,
не ленитесь ставить лайки и делиться с друзьями.

Комментариев: 4

Статья информативная. Но у меня вопрос. Насколько сильно эти файлы мешают работе системы? Стоит ли вообще заморачиваться?

Если вы работаете на маке, то ничего удалять не нужно, а вот пользователей Windows их наличие сильно тревожит. В принципе можно не заморачиваться.

Ценно. а то уже начал ЕЛОЗИТЬ и разными утилитами сканировать ))))

Ввел команды, настроил самба-сервер, все вроде ок, но теперь макбук при редактировании файлов майкрософт офис в сетевой папке спамит созданием папок с названием редактируемого файла и чем-то типа хэша в конце имени папки, что хто такое и можно ли отключить любой спам файлами от мака?

I understand I can use find . -name ".DS_Store" to find all the .DS_Store files in the current folder and all subfolders. But how could I delete them from command line simultaneously? I found it's really annoying to switch back and forth to all folders and delete it one by one.

931 4 4 gold badges 15 15 silver badges 35 35 bronze badges 1,968 2 2 gold badges 16 16 silver badges 20 20 bronze badges

8 Answers 8

find can do that. Just add -delete :


6,473 3 3 gold badges 30 30 silver badges 38 38 bronze badges You need to fix file name case to be ".DS_Store", if used ".DS_STORE" it will not work as file names are case sensitive. I would add this line to my .bashrc_profile, to clean the files every time I start the shell. How do I make it less verbose, or totaly quiet?

This will delete all the files named .DS_Store in the current path while also displaying their relative paths

10.4k 4 4 gold badges 27 27 silver badges 54 54 bronze badges


@kelin uh, how is this a link-only answer when there is no link?

Here is how to remove recursively the .DS_Store file

Then finally, type in the below command:

21.8k 50 50 gold badges 69 69 silver badges 105 105 bronze badges


You can also use extended globbing ( ** ):

in zsh, bash 4 and similar shells (if not enabled, activate by: shopt -s globstar ).

128k 70 70 gold badges 620 620 silver badges 655 655 bronze badges

The best way to do this cleanly is using:

This removes the files, hides "permission denied" errors (while keeping other errors), printing out a clean list of files removed.


Make a new file with a text editor, copy and paste the following text into it, and save it with the ".sh" file extension, then open the file with Terminal. Make sure the text editor is actually saving the raw text and not saving the file as a Rich Text Format file or some other text file format with additional information in the file.


This wasn't exactly the question, but if you wanna actually zip the directory without them .DS_STORE files, this works a treat.

All the answers above work but there is a bigger problem if one is using mac and still on mac. The described lines do delete all the DS_Store files but Finder recreates them immediately again because that is the default behaviour. You can read about how this all works here. To quote from there if you are on mac, you should remove them only if you really need:

If you don’t have a particular reason to delete these .DS_Store files (windows sharing might be a solid reason,) it’s best to leave them “as is.” There’s no performance benefit in deleting .DS_Store files. They are harmless files that don’t usually cause any problems. Remember that the .DS_Store file saves your personalized folder settings, such as your icon arrangement and column sortings. And that’s why you normally don’t want to delete them but rather HIDE them.

How can I remove those annoying Mac OS X .DS_Store files from a Git repository?


50.4k 24 24 gold badges 153 153 silver badges 162 162 bronze badges 109k 45 45 gold badges 191 191 silver badges 235 235 bronze badges Think this is the same in many versions of MacOS, not only Mac OS X.

28 Answers 28

Remove existing files from the repository:

to the file .gitignore , which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory:

Then commit the file to the repo:


10.9k 7 7 gold badges 39 39 silver badges 52 52 bronze badges 76.5k 20 20 gold badges 107 107 silver badges 134 134 bronze badges @CharlieS Yes, if the pattern does not contain a slash, it is matched against the file name in all directories.

Combining benzado and webmat's answers, updating with git rm , not failing on files found that aren't in repo, and making it paste-able generically for any user:

7,128 2 2 gold badges 45 45 silver badges 49 49 bronze badges I found that when using a git repo in my home directory (AKA a "dotfiles" repo), having

The best solution to tackle this issue is to Globally ignore these files from all the git repos on your system. This can be done by creating a global gitignore file like:

Adding Rules for ignoring files like:

Now, add this file to your global git config:

Removed Icons as they might need to be committed as application assets.

5,655 4 4 gold badges 26 26 silver badges 29 29 bronze badges I would recommend that each developer deals with his os specific files in his own .global_ignore, that way the project .gitignore is project specific. must run: git add .gitignore_global , in order another programmers have that file too in his local environment ?

/.gitignore too (not certain!). Oh and I have repos that have .jar files and .log files too so that could be a problem for some (and I imagine other people different extensions added here).

As I am new to get I find this to be a fantastic resource for me at first glance, but I was wondering if there is a video or article someone could point me to so I can understand the reasons behind why the file types are typically ignored. Thanks in advance!

In some situations you may also want to ignore some files globally. For me, .DS_Store is one of them. Here's how:

(Or any file of your choice)

Then edit the file just like a repo's .gitignore. Note that I think you have to use an absolute path.

58.2k 18 18 gold badges 157 157 silver badges 162 162 bronze badges 52.6k 12 12 gold badges 53 53 silver badges 59 59 bronze badges

If you are unable to remove the files because they have changes staged use:

9,959 3 3 gold badges 35 35 silver badges 33 33 bronze badges

Top voted answer is awesome, but helping out the rookies like me, here is how to create the .gitignore file, edit it, save it, remove the files you might have already added to git, then push up the file to Github.

Create the .gitignore file

To create a .gitignore file, you can just touch the file which creates a blank file with the specified name. We want to create the file named .gitignore so we can use the command:

Ignore the files

Now you have to add the line which tells git to ignore the DS Store files to your .gitignore. You can use the nano editor to do this.

Nano is nice because it includes instructions on how to get out of it. ( Ctrl - O to save, Ctrl - X to exit)

Copy and paste some of the ideas from this Github gist which lists some common files to ignore. The most important ones, to answer this question, would be:

This Github article also has some general ideas and guidelines.

Remove the files already added to git

Finally, you need to actually remove those DS Store files from your directory.

Use this great command from the top voted answer. This will go through all the folders in your directory, and remove those files from git.

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

Push .gitignore up to Github

Last step, you need to actually commit your .gitignore file.

git add .gitignore

git commit -m '.DS_Store banished!'

6,814 3 3 gold badges 54 54 silver badges 60 60 bronze badges I found my own answer 2 years later and used it. Good work past me. :)

Open terminal and type "cd < ProjectPath >"

Remove existing files: find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

Add this .DS_Store

Enter to save file

git add .gitignore

git commit -m '.DS_Store removed.'

nano .gitignore creates the file if not present, this command should be executed from project root folder @Saif Not necessarily. You can have .gitignore in any directory where you want to exclude some files in a subdirectory but not the root directory. I have this in a number of my repos for example.

I had to change git-rm to git rm in the above to get it to work:

32.9k 14 14 gold badges 99 99 silver badges 134 134 bronze badges

Use this command to remove the existing files:

Then add .DS_Store to .gitignore

Sometimes .DS_Store files are there at remote repository, but not visible at your local project folders. To fix this, we need to remove all cached files and add again.

Step 1: Add this to .gitignore file.

Step 2: Remove the cached files and add again using these commands.


Best way to get rid of this file forever and never have to worry about it again is

make a global .gitignore file:

And let git know that you want to use this file for all of your repositories:

git config --global core.excludesfile

/.gitignore_global And that’s it! .DS_Store is out of your way.


delete them using git-rm , and then add .DS_Store to .gitignore to stop them getting added again. You can also use blueharvest to stop them getting created all together

11k 12 12 gold badges 51 51 silver badges 62 62 bronze badges

The following worked best for me. Handled unmatched files, and files with local modifications. For reference, this was on a Mac 10.7 system running git 1.7.4.4.

Find and remove:

I also globally ignore .DS_Store across all repositories by setting a global core.excludesfile.

First, create the file (if one doesn't already exist):

Then add the following line and save:

Now configure git to respect the file globally:

I'm a bit late to the party, but I have a good answer. To remove the .DS_Store files, use the following commands from a terminal window, but be very careful deleting files with 'find'. Using a specific name with the -name option is one of the safer ways to use it:

You can leave off the "-delete" if you want to simply list them before and after. That will reassure you that they're gone.

With regard to the

/.gitignore_global advice: be careful here. You want to place that nice file into .gitignore within the top level of each workarea and commit it, so that anyone who clones your repo will gain the benefit of its use.

I found that the following line from snipplr does best on wiping all .DS_Store , including one that has local modifications.

--cached option, keeps your local .DS_Store since it gonna be reproduced anyway.

And just like mentioned all above, add .DS_Store to .gitignore file on the root of your project. Then it will be no longer in your sight (of repos).


3,614 5 5 gold badges 25 25 silver badges 46 46 bronze badges

Step 1

This will remove every .DS_Store file in a directory (including subdirectories)

Step 2

Add this to .gitignore to prevent any DS_Store files in the root directory and every subdirectory from going to git!

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".


20.5k 8 8 gold badges 96 96 silver badges 142 142 bronze badges

It deletes all files whose names end with .DS_Store , including ._.DS_Store .


19.4k 5 5 gold badges 37 37 silver badges 58 58 bronze badges 109k 45 45 gold badges 191 191 silver badges 235 235 bronze badges asterisk should be there because i found .DS_Store and ._.DS_Store files on my mac system. @MutantMahesh. In that case, you need "*.DS_Store" , so that the asterisk is passed to find rather than expanded by the shell.

For some reason none of the above worked on my mac.

My solution is from the terminal run:

Then run following command:

When initializing your repository, skip the git command that contains

and it shouldn't be an issue.

This worked for me, combo of two answers from above:

  • $ git rm --cached -f *.DS_Store
  • $ git commit -m "filter-branch --index-filter 'git rm --cached --ignore-unmatch .DS_Store"
  • $ git push origin master --force


Remove ignored files:

19.6k 32 32 gold badges 113 113 silver badges 186 186 bronze badges

add this to your file .gitignore

save this and make commit

and now you ignore this for all your commits


create a .gitignore file using command touch .gitignore

and add the following lines in it

save the .gitignore file and then push it in to your git repo.


3,614 5 5 gold badges 25 25 silver badges 46 46 bronze badges


There are a few solutions to resolve this problem. To avoid creating .DS_Store files, do not to use the OS X Finder to view folders. An alternative way to view folders is to use UNIX command line. To remove the .DS_Store files a third-party product called DS_Store Terminator can be used. To delete the .DS_Store files from the entire system a UNIX shell command can be used. Launch Terminal from Applications:Utilities At the UNIX shell prompt enter the following UNIX command: sudo find / -name ".DS_Store" -depth -exec rm <> \; When prompted for a password enter the Mac OS X Administrator password.

This command is to find and remove all occurrences of .DS_Store starting from the root (/) of the file system through the entire machine. To configure this command to run as a scheduled task follow the steps below: Launch Terminal from Applications:Utilities At the UNIX shell prompt enter the following UNIX command:

sudo crontab -e When prompted for a password enter the Mac OS X Administrator password. Once in the vi editor press the letter I on your keyboard once and enter the following:

15 1 * * * root find / -name ".DS_Store" -depth -exec rm <> \;

This is called crontab entry, which has the following format:

Minute Hour DayOfMonth Month DayOfWeek User Command.

The crontab entry means that the command will be executed by the system automatically at 1:15 AM everyday by the account called root.

The command starts from find all the way to . If the system is not running this command will not get executed.

To save the entry press the Esc key once, then simultaneously press Shift + z+ z.

Читайте также: