Удалить файлы ds store
How can I remove those annoying Mac OS X .DS_Store files from a Git repository?
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:
It's really trivial, but using -exec will launch git-rm once for every .DS_Store file, while xargs will put all the paths on one command line. Mostly I prefer xargs because I don't have to worry about escaping a lot of special characters.
@Andrew: I don't agree. It would never be useful for a .DS_Store file to be checked in, so it makes more sense as a repository-wide, all-users setting, rather than something each Mac user needs to remember to set on her own machine.
Does adding .DS_Store to .gitignore work recursively? That is, will it ignore some/level/of/folders/.DS_Store as well?
@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:
I found that when using a git repo in my home directory (AKA a "dotfiles" repo), having ~/.gitignore as my global excludes file is a pain. There are files that I want to exclude from my home directory that I don't want to ignore globally. I use ~/.gitexcludes instead via the same directive: core.excludesfile
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.
You can also add above rules in your repository's .gitignore. This would keep away these files at repo level if there are multiple contributors to your project. However, in such cases, .gitignore should deal with every OS' specific files etc if different developers are using different OS. Like rules for linux, OSX etc.
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 ?
@stackdave No. That file isn't even under git control. That's in the home directory and they would have to update their git config too. There isn't even a reason to do it this way. No need to make a new file when there already exists the files for the same purpose. Each directory can have a .gitignore and there's also the repo specific info/exclude. Also - though I'm vague on this one - I think you can use ~/.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.
If you are unable to remove the files because they have changes staged use:
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!'
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.
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:
Use this command to remove the existing files:
Then add .DS_Store to .gitignore
Best way to get rid of this file forever and never have to worry about it again is
make a global .gitignore file:
echo .DS_Store >> ~/.gitignore_global
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
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:
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".
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.
Indeed: whenever you are going to do a destructive command it is arguably best to start out by printing the files that will be affected before actually doing the destructive command. It can save you a great deal of pain (esp if you're one who doesn't backup though even those of us who regularly backup can be saved time this way)!
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).
For some reason none of the above worked on my mac.
My solution is from the terminal run:
Then run following command:
that's because you are trying to remove it from the local. whereas the question asks about to remove it from git.
It deletes all files whose names end with .DS_Store , including ._.DS_Store .
@MutantMahesh. In that case, you need "*.DS_Store" , so that the asterisk is passed to find rather than expanded by the shell.
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:
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.
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.
Corrupted .DS_Store files can prevent OneDrive from syncing correctly. Deleting the corrupted files can help restore normal sync operation.
No data is lost by deleting the corrupted files as Mac Finder only creates .DS_Store files to store viewing options, such as the positions of icons, size of the Finder window, and window backgrounds.
To delete a corrupted .DS_Store file, you will need to use Terminal.app.
Note: You must be logged into macOS as an administrator.
Open a new Finder window and navigate to the Applications folder on the left.
Open the Utilities folder, then double-click the Terminal application.
Give yourself super-user (root) permissions in Terminal so you can use the commands needed to delete .DS_Store files.
In Terminal, type sudo ls then press Return on your keyboard.
When Terminal prompts you for a password, enter your administrator account password. If you don't have a password, leave it blank.
Note: For security reasons, macOS won't show any sign that you are typing your password. Just type normally, even though nothing shows.
Navigate to the folder that is not syncing correctly.
In Terminal, type cd followed by a space.
Find the folder with the issue but do not open it. Instead, drag its icon into Terminal and watch it complete the path for you, then press Return.
Remove the .DS_Store folder and all its contents.
Caution: Make sure you are deleting the correct folder.
Type rm -f .DS_Store and press Return.
Note: Terminal will give no indication that this has been completed. It will only return a message if the command did not work.
Need more help?
Contact Support
For help with your Microsoft account and subscriptions, visit Account & Billing Help.
For technical support, go to Contact Microsoft Support, enter your problem and select Get Help. If you still need help, select Contact Support to be routed to the best support option.
Повреждение .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.
Дополнительные сведения
Чтобы получить техническую поддержку, Обратитесь в службу поддержки Майкрософт, введите свою проблему и выберите Техническая поддержка. Если вам по-прежнему нужна помощь, выберитеОбратитесь в службу поддержки, чтобы получить наилучший вариант поддержки.
Примечание: Эта страница переведена автоматически, поэтому ее текст может содержать неточности и грамматические ошибки. Для нас важно, чтобы эта статья была вам полезна. Была ли информация полезной? Для удобства также приводим ссылку на оригинал (на английском языке).
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. ВВОДИТЕ ПРАВИЛЬНО эту команду.
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.
8 Answers 8
find can do that. Just add -delete :
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
@ppperry, this is automatic message from the review. I voted to delete you answer, because it doesn't add anything important comparing to the accepted one.
Here is how to remove recursively the .DS_Store file
Then finally, type in the below command:
You can also use extended globbing ( ** ):
in zsh, bash 4 and similar shells (if not enabled, activate by: shopt -s globstar ).
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.
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.
Читайте также: